pyMOR - Model Order Reduction with python

pyMOR is a software library for building model order reduction applications with the Python programming language. Implemented algorithms include reduced basis methods for parametric linear and non-linear problems, as well as system-theoretic methods such as balanced truncation or IRKA. All algorithms in pyMOR are formulated in terms of abstract interfaces for seamless integration with external PDE solver packages. Moreover, pure Python implementations of finite element and finite volume discretizations using the NumPy/SciPy scientific computing stack are provided for getting started quickly.

Getting started

Installation

pyMOR can be easily installed via pip:

pip install --upgrade pip  # make sure that pip is reasonably new
pip install pymor[full]

For Linux we provide binary wheels, so no further system packages should be required. The following optional packages must be installed separately:

# for support of MPI distributed models and parallelization of
# greedy algorithms (requires MPI development headers and a C compiler)
pip install mpi4py

# dense matrix equation solver for system-theoretic MOR methods,
# required for H-infinity norm calculation (requires OpenBLAS headers and a Fortran compiler)
pip install slycot

# sparse matrix equation solver for system-theoretic MOR methods
# (other backends available)
open https://www.mpi-magdeburg.mpg.de/projects/mess
# download and install pymess wheel for your architecture

We recommend installation of pyMOR in a virtual environment. Please take a look at our README file for more detailed installation instructions and a guide to setup a development environment for working on pyMOR itself.

Trying it out

While we consider pyMOR mainly as a library for building MOR applications, we ship a few example scripts. These can be found in the src/pymordemos directory of the source repository (some are available as Jupyter notebooks in the notebooks directory). Try launching one of them using the pymor-demo script:

pymor-demo thermalblock --plot-err --plot-solutions 3 2 3 32

The demo scripts can also be launched directly from the source tree:

./thermalblock.py --plot-err --plot-solutions 3 2 3 32

This will reduce the so called thermal block problem using the reduced basis method with a greedy basis generation algorithm. The thermal block problem consists in solving the stationary heat equation

- ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = 1     for x in Ω
                  u(x, μ)   = 0     for x in ∂Ω

on the domain Ω = [0,1]^2 for the unknown u. The domain is partitioned into XBLOCKS x YBLOCKS blocks (XBLOCKS and YBLOCKS are the first two arguments to thermalblock.py). The thermal conductivity d(x, μ) is constant on each block (i,j) with value μ_ij:

(0,1)------------------(1,1)
|        |        |        |
|  μ_11  |  μ_12  |  μ_13  |
|        |        |        |
|---------------------------
|        |        |        |
|  μ_21  |  μ_22  |  μ_23  |
|        |        |        |
(0,0)------------------(1,0)

The real numbers μ_ij form the XBLOCKS x YBLOCKS - dimensional parameter on which the solution depends.

Running thermalblock.py will first produce plots of two detailed solutions of the problem for different randomly chosen parameters using linear finite elements. (The size of the grid can be controlled via the --grid parameter. The randomly chosen parameters will actually be the same for each run, since a the random generator is initialized with a fixed default seed in new_random_state.)

After closing the window, the reduced basis for model order reduction is generated using a greedy search algorithm with error estimator. The third parameter SNAPSHOTS of thermalblock.py determines how many different values per parameter component μ_ij should be considered. I.e. the parameter training set for basis generation will have the size SNAPSHOTS^(XBLOCKS x YBLOCKS). After the basis of size 32 (the last parameter) has been computed, the quality of the obtained reduced model (on the 32-dimensional reduced basis space) is evaluated by comparing the solutions of the reduced and detailed models for new, randomly chosen parameters. Finally, plots of the detailed and reduced solutions, as well as the difference between the two, are displayed for the random parameter which maximises reduction error.

The thermalblock demo explained

In the following we will walk through the thermal block demo step by step in an interactive Python shell. We assume that you are familiar with the reduced basis method and that you know the basics of Python programming as well as working with NumPy. (Note that our code will differ a bit from thermalblock.py as we will hardcode the various options the script offers and leave out some features.)

First, start a Python shell. We recommend using IPython

ipython

You can paste the following input lines starting with >>> by copying them to the system clipboard and then executing

%paste

inside the IPython shell.

First, we will import the most commonly used methods and classes of pyMOR by executing:

>>> from pymor.basic import *

Next we will instantiate a class describing the analytical problem we want so solve. In this case, a thermal_block_problem:

>>> p = thermal_block_problem(num_blocks=(3, 2))

We want to discretize this problem using the finite element method. We could do this by hand, creating a Grid, instatiating DiffusionOperatorP1 finite element diffusion operators for each subblock of the domain, forming a LincombOperator to represent the affine decomposition, instantiating a L2ProductFunctionalP1 as right hand side, and putting it all together into a StationaryDiscretization. However, since thermal_block_problem returns a StationaryProblem, we can use a predifined discretizer to do the work for us. In this case, we use discretize_stationary_cg:

>>> d, d_data = discretize_stationary_cg(p, diameter=1./100.)

d is the StationaryDiscretization which has been created for us, whereas d_data contains some additional data, in particular the Grid and the BoundaryInfo which have been created during discretization. We can have a look at the grid,

>>> print(d_data['grid'])
Tria-Grid on domain [0,1] x [0,1]
x0-intervals: 100, x1-intervals: 100
elements: 40000, edges: 60200, vertices: 20201

and, as always, we can display its class documentation using help(d_data['grid']).

Let’s solve the thermal block problem and visualize the solution:

>>> U = d.solve([1.0, 0.1, 0.3, 0.1, 0.2, 1.0])
>>> d.visualize(U, title='Solution')
01:11 StationaryDiscretization: Solving ThermalBlock((3, 2))_CG for {diffusion: [1.0, 0.1, 0.3, 0.1, 0.2, 1.0]} ...

Each class in pyMOR that describes a Parameter dependent mathematical object, like the StationaryDiscretization in our case, derives from Parametric and determines the Parameters it expects during __init__ by calling build_parameter_type. The resulting ParameterType is stored in the object’s parameter_type attribute. Let us have a look:

>>> print(d.parameter_type)
{diffusion: (2, 3)}

This tells us, that the Parameter which solve expects should be a dictionary with one key 'diffusion' whose value is a NumPy array of shape (2, 3), corresponding to the block structure of the problem. However, by using the parse_parameter method, pyMOR is smart enough to correctly parse the input [1.0, 0.1, 0.3, 0.1, 0.2, 1.0].

Next we want to use the greedy algorithm to reduce the problem. For this we need to choose a reductor which will keep track of the reduced basis and perform the actual RB-projection. We will use CoerciveRBReductor, which will also assemble an error estimator to estimate the reduction error. This will significantly speed up the basis generation, as we will only need to solve the high-dimensional problem for those parameters in the training set which are actually selected for basis extension. To control the condition of the reduced system matrix, we must ensure that the generated basis is orthonormal w.r.t. the H1_0-product on the solution space. For this we pass the h1_0_semi_product attribute of the discretization as inner product to the reductor, which will also use it for computing the Riesz representatives required for error estimation. Moreover, we have to provide the reductor with a ParameterFunctional which computes a lower bound for the coercivity of the problem for a given parameter.

>>> reductor = CoerciveRBReductor(
...     d,
...     product=d.h1_0_semi_product,
...     coercivity_estimator=ExpressionParameterFunctional('min(diffusion)', d.parameter_type)
... )

Moreover, we need to select a Parameter training set. The discretization d already comes with a ParameterSpace which it has inherited from the analytical problem. We can sample our parameters from this space, which is a CubicParameterSpace. E.g.:

>>> samples = d.parameter_space.sample_uniformly(4)
>>> print(samples[0])
{diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]}

Now we start the basis generation:

>>> greedy_data = greedy(d, reductor, samples,
...                      use_estimator=True,
...                      max_extensions=32)
16:52 greedy: Started greedy search on 4096 samples
16:52 greedy: Reducing ...
16:52 |   CoerciveRBReductor: RB projection ...
16:52 |   CoerciveRBReductor: Assembling error estimator ...
16:52 |   |   ResidualReductor: Estimating residual range ...
16:52 |   |   |   estimate_image_hierarchical: Estimating image for basis vector -1 ...
16:52 |   |   |   estimate_image_hierarchical: Orthonormalizing ...
16:52 |   |   ResidualReductor: Projecting residual operator ...
16:52 greedy: Estimating errors ...
16:55 greedy: Maximum error after 0 extensions: 1.8745731821515579 (mu = {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]})
16:55 greedy: Computing solution snapshot for mu = {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} ...
16:55 |   StationaryDiscretization: Solving ThermalBlock((3, 2))_CG for {diffusion: [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]} ...
16:55 greedy: Extending basis with solution snapshot ...
                 ...
                 ...
18:57 greedy: Maximum number of 32 extensions reached.
18:57 greedy: Reducing once more ...
18:57 |   CoerciveRBReductor: RB projection ...
18:57 |   CoerciveRBReductor: Assembling error estimator ...
18:57 |   |   ResidualReductor: Estimating residual range ...
18:57 |   |   |   estimate_image_hierarchical: Estimating image for basis vector 31 ...
18:57 |   |   |   estimate_image_hierarchical: Orthonormalizing ...
18:57 |   |   |   |   gram_schmidt: Removing vector 180 of norm 1.7588304501544013e-15
18:57 |   |   |   |   gram_schmidt: Orthonormalizing vector 181 again
18:57 |   |   |   |   gram_schmidt: Orthonormalizing vector 182 again
18:57 |   |   |   |   gram_schmidt: Orthonormalizing vector 183 again
18:58 |   |   |   |   gram_schmidt: Orthonormalizing vector 184 again
18:58 |   |   |   |   gram_schmidt: Orthonormalizing vector 185 again
18:58 |   |   |   |   gram_schmidt: Orthonormalizing vector 186 again
18:58 |   |   ResidualReductor: Projecting residual operator ...
18:58 greedy: Greedy search took 126.14163041114807 seconds

The max_extensions parameter defines how many basis vectors we want to obtain. greedy_data is a dictionary containing various data that has been generated during the run of the algorithm:

>>> print(greedy_data.keys())
dict_keys(['rd', 'max_errs', 'extensions', 'max_err_mus', 'time'])

The most important items is 'rd' which holds the reduced Discretization obtained from applying our reductor with the final reduced basis.

>>> rd = greedy_data['rd']

All vectors in pyMOR are stored in so called VectorArrays. For example the solution U computed above is given as a VectorArray of length 1. For the reduced basis we have:

>>> print(type(reductor.RB))
<class 'pymor.vectorarrays.numpy.NumpyVectorArray'>
>>> print(len(reductor.RB))
32
>>> print(reductor.RB.dim)
20201

Let us check if the reduced basis really is orthonormal with respect to the H1-product. For this we use the apply2 method:

>>> import numpy as np
>>> gram_matrix = reductor.RB.gramian(d.h1_0_semi_product)
>>> print(np.max(np.abs(gram_matrix - np.eye(32))))
3.0088616060491846e-14

Looks good! We can now solve the reduced model for the same parameter as above. The result is a vector of coefficients w.r.t. the reduced basis, which is currently stored in rb. To form the linear combination, we can use the reconstruct method of the reductor:

>>> u = rd.solve([1.0, 0.1, 0.3, 0.1, 0.2, 1.0])
>>> print(u)
[[  5.79477471e-01   5.91289054e-02   1.89924036e-01   1.89149529e-02
    1.81103127e-01   2.69920752e-02  -1.79611519e-01   7.99676272e-03
    1.54092560e-01   5.76326362e-02   1.97982347e-01  -2.13775254e-02
    3.12892660e-02  -1.27037440e-01  -1.51352508e-02   3.36101087e-02
    2.05779889e-02  -4.96445984e-03   3.21176662e-02  -2.52674851e-02
    2.92150040e-02   3.23570362e-03  -4.14288199e-03   5.48325425e-03
    4.10728945e-03   1.59251955e-03  -9.23470903e-03  -2.57483574e-03
   -2.52451212e-03  -5.08125873e-04   2.71427033e-03   5.83210112e-05]]
>>> U_red = reductor.reconstruct(u)
>>> print(U_red.dim)
20201

Finally we compute the reduction error and display the reduced solution along with the detailed solution and the error:

>>> ERR = U - U_red
>>> print(ERR.norm(d.h1_0_semi_product))
[0.00473238]
>>> d.visualize((U, U_red, ERR),
...             legend=('Detailed', 'Reduced', 'Error'),
...             separate_colorbars=True)

We can nicely observe that, as expected, the error is maximized along the jumps of the diffusion coefficient.

Learning more

As a next step, you should read our Technical Overview which discusses the most important concepts and design decisions behind pyMOR. After that you should be ready to delve into the reference documentation.

Should you have any problems regarding pyMOR, questions or feature requests, do not hesitate to contact us at our mailing list!

Technical Overview

Three Central Classes

From a bird’s eye perspective, pyMOR is a collection of generic algorithms operating on objects of the following types:

VectorArrays

Vector arrays are ordered collections of vectors. Each vector of the array must be of the same dimension. Vectors can be copied to a new array, appended to an existing array or deleted from the array. Basic linear algebra operations can be performed on the vectors of the array: vectors can be scaled in-place, the BLAS axpy operation is supported and inner products between vectors can be formed. Linear combinations of vectors can be formed using the lincomb method. Moreover, various norms can be computed and selected dofs of the vectors can be extracted for empirical interpolation. To act on subsets of vectors of an array, arrays can be indexed with an integer, a list of integers or a slice, in each case returning a new VectorArray which acts as a modifiable view onto the respective vectors in the original array. As a convenience, many of Python’s math operators are implemented in terms of the interface methods.

Note that there is not the notion of a single vector in pyMOR. The main reason for this design choice is to take advantage of vectorized implementations like NumpyVectorArray which internally store the vectors as two-dimensional NumPy arrays. As an example, the application of a linear matrix based operator to an array via the apply method boils down to a call to NumPy’s optimized dot method. If there were only lists of vectors in pyMOR, the above matrix-matrix multiplication would have to be expressed by a loop of matrix-vector multiplications. However, when working with external solvers, vector arrays will often be given as lists of individual vector objects. For this use-case we provide ListVectorArray, a VectorArray based on a Python list of vectors.

Associated to each vector array is a VectorSpace which acts as a factory for new arrays of a given type. New vector arrays can be created using the zeros and empty methods. To wrap the raw objects of the underlying linear algebra backend into a new VectorArray, make_array is used.

The data needed to define a new VectorSpace largely depends on the implementation of the underlying backend. For NumpyVectorSpace, the only required datum is the dimension of the contained vectors. VectorSpaces for other backends could, e.g., hold a socket for communication with a specific PDE solver instance. Additionally, each VectorSpace has a string id, defaulting to None, which is used to signify the mathematical identity of the given space.

Two arrays in pyMOR are compatible (e.g. can be added) if they are from the same VectorSpace. If a VectorArray is contained in a given VectorSpace can be tested with the in operator.

Operators

The main property of operators in pyMOR is that they can be applied to VectorArrays resulting in a new VectorArray. For this operation to be allowed, the operator’s source VectorSpace must be identical with the VectorSpace of the given array. The result will be a vector array from the range space. An operator can be linear or not. The apply_inverse method provides an interface for (linear) solvers.

Operators in pyMOR are also used to represent bilinear forms via the apply2 method. A functional in pyMOR is simply an operator with NumpyVectorSpace(1) as range. Dually, a vector-like operator is an operator with NumpyVectorSpace(1) as source. Such vector-like operators are used in pyMOR to represent Parameter dependent vectors such as the initial data of an InstationaryDiscretization. For linear functionals and vector-like operators, the as_vector method can be called to obtain a vector representation of the operator as a VectorArray of length 1.

Linear combinations of operators can be formed using a LincombOperator. When such a linear combination is assembled, assemble_lincomb is called to ensure that, for instance, linear combinations of operators represented by a matrix lead to a new operator holding the linear combination of the matrices.

Default implementations for many methods of the operator interface can be found in OperatorBase. Base classes for NumPy-based operators can be found in pymor.operators.numpy. Several methods for constructing new operators from existing ones are contained in pymor.operators.constructions.

Discretizations

Discretizations in pyMOR encode the mathematical structure of a given discrete problem by acting as container classes for operators. Each discretization object has operators, products dictionaries holding the Operators which appear in the formulation of the discrete problem. The keys in these dictionaries describe the role of the respective operator in the discrete problem.

Apart from describing the discrete problem, discretizations also implement algorithms for solving the given problem, returning VectorArrays from the solution_space. The solution can be cached, s.t. subsequent solving of the problem for the same parameter reduces to looking up the solution in pyMOR’s cache.

While special discretization classes may be implemented which make use of the specific types of operators they contain (e.g. using some external high-dimensional solver for the problem), it is generally favourable to implement the solution algorithms only through the interfaces provided by the operators contained in the discretization, as this allows to use the same discretization class to solve high-dimensional and reduced problems. This has been done for the simple stationary and instationary discretizations found in pymor.discretizations.basic.

Discretizations can also implement estimate and visualize methods to estimate the discretization or model reduction error of a computed solution and create graphic representations of VectorArrays from the solution_space.

Base Classes

While VectorArrays are mutable objects, both Operators and Discretizations are immutable in pyMOR: the application of an Operator to the same VectorArray will always lead to the same result, solving a Discretization for the same parameter will always produce the same solution array. This has two main benefits:

  1. If multiple objects/algorithms hold references to the same Operator or Discretization, none of the objects has to worry that the referenced object changes without their knowledge.
  2. It becomes affordable to generate persistent keys for caching of computation results by generating state ids which uniquely identify the object’s state. Since the state cannot change, these ids have to be computed only once for the lifetime of the object.

A class can be made immutable in pyMOR by deriving from ImmutableInterface, which ensures that write access to the object’s attributes is prohibited after __init__ has been executed. However, note that changes to private attributes (attributes whose name starts with _) are still allowed. It lies in the implementors responsibility to ensure that changes to these attributes do not affect the outcome of calls to relevant interface methods. As an example, a call to enable_caching will set the objects private __cache_region attribute, which might affect the speed of a subsequent solve call, but not its result.

Of course, in many situations one may wish to change properties of an immutable object, e.g. the number of timesteps for a given discretization. This can be easily achieved using the with_ method every immutable object has: a call of the form o.with_(a=x, b=y) will return a copy of o in which the attribute a now has the value x and the attribute b the value y. It can be generally assumed that calls to with_ are inexpensive. The set of allowed arguments can be found in the with_arguments attribute.

All immutable classes in pyMOR and most other classes derive from BasicInterface which, through its meta class, provides several convenience features for pyMOR. Most notably, every subclass of BasicInterface obtains its own logger instance with a class specific prefix.

Creating Discretizations

pyMOR ships a small (and still quite incomplete) framework for creating finite element or finite volume discretizations based on the NumPy/Scipy software stack. To end up with an appropriate Discretization, one starts by instantiating an analytical problem which describes the problem we want to discretize. analytical problems contain Functions which define the analytical data functions associated with the problem and a DomainDescription that provides a geometrical definition of the domain the problem is posed on and associates a boundary type to each part of its boundary.

To obtain a Discretization from an analytical problem we use a discretizer. A discretizer will first mesh the computational domain by feeding the DomainDescription into a domaindiscretizer which will return the Grid along with a BoundaryInfo associating boundary entities with boundary types. Next, the Grid, BoundaryInfo and the various data functions of the analytical problem are used to instatiate finite element or finite volume operators. Finally these operators are used to instatiate one of the provided Discretization classes.

In pyMOR, analytical problems, Functions, DomainDescriptions, BoundaryInfos and Grids are all immutable, enabling efficient disk caching for the resulting Discretizations, persistent over various runs of the applications written with pyMOR.

While pyMOR’s internal discretizations are useful for getting started quickly with model reduction experiments, pyMOR’s main goal is to allow the reduction of discretizations provided by external solvers. In order to do so, all that needs to be done is to provide VectorArrays, Operators and Discretizations which interact appropriately with the solver. pyMOR makes no assumption on how the communication with the solver is managed. For instance, communication could take place via a network protocol or job files. In particular it should be stressed that in general no communication of high-dimensional data between the solver and pyMOR is necessary: VectorArrays can merely hold handles to data in the solver’s memory or some on-disk database. Where possible, we favour, however, a deep integration of the solver with pyMOR by linking the solver code as a Python extension module. This allows Python to directly access the solver’s data structures which can be used to quickly add features to the high-dimensional code without any recompilation. A minimal example for such an integration using pybindgen can be found in the src/pymordemos/minimal_cpp_demo directory of the pyMOR repository. Bindings for FEnicS and NGSolve packages are available in the bindings.fenics and bindings.ngsolve modules. The pymor-deal.II repository contains experimental bindings for deal.II.

Parameters

pyMOR classes implement dependence on a parameter by deriving from the Parametric mix-in class. This class gives each instance a parameter_type attribute describing the form of Parameters the relevant methods of the object (apply, solve, evaluate, etc.) expect. A Parameter in pyMOR is basically a Python dict with strings as keys and NumPy arrays as values. Each such value is called a Parameter component. The ParameterType of a Parameter is simply obtained by replacing the arrays in the Parameter with their shape. I.e. a ParameterType specifies the names of the parameter components and their expected shapes.

The ParameterType of a Parametric object is determined by the class implementor during __init__ via a call to build_parameter_type, which can be used to infer the ParameterType from the ParameterTypes of objects the given object depends upon. I.e. an Operator implementing the L2-product with some Function will inherit the ParameterType of the Function.

Reading the reference documentation on pyMOR’s parameter handling facilities is strongly advised for implementors of Parametric classes.

Defaults

pyMOR offers a convenient mechanism for handling default values such as solver tolerances, cache sizes, log levels, etc. Each default in pyMOR is the default value of an optional argument of some function. Such an argument is made a default by decorating the function with the defaults decorator:

@defaults('tolerance')
def some_algorithm(x, y, tolerance=1e-5)
    ...

Default values can be changed by calling set_defaults. By calling print_defaults a summary of all defaults in pyMOR and their values can be printed. A configuration file with all defaults can be obtained with write_defaults_to_file. This file can then be loaded, either programmatically or automatically by setting the PYMOR_DEFAULTS environment variable.

As an additional feature, if None is passed as value for a function argument which is a default, its default value is used instead of None. This allows writing code of the following form:

def method_called_by_user(U, V, tolerance_for_algorithm=None):
    ...
    algorithm(U, V, tolerance=tolerance_for_algorithm)
    ...

See the defaults module for more information.

RuleTables

Many algorithms in pyMOR can be seen as transformations acting on trees of Operators. One example is the structure-preserving (Petrov-)Galerkin projection of Operators performed by the project method. For instance, a LincombOperator is projected by replacing all its children (the Operators forming the affine decomposition) with projected Operators.

During development of pyMOR, it turned out that using inheritance for selecting the action to be taken to project a specific operator (i.e. single dispatch based on the class of the to-be-projected Operator) is not sufficiently flexible. With pyMOR 0.5 we have introduced algorithms which are based on RuleTables instead of inheritance. A RuleTable is simply an ordered list of rules, i.e. pairs of conditions to match with corresponding actions. When a RuleTable is applied to an object (e.g. an Operator), the action associated with the first matching rule in the table is executed. As part of the action, the RuleTable can be easily applied recursively to the children of the given object.

This approach has several advantages over an inheritance-based model:

  • Rules can match based on the class of the object, but also on more general conditions, i.e. the name of the Operator or being linear and non-parametric.
  • The entire mathematical algorithm can be specified in a single file even when the definition of the possible classes the algorithm can be applied to is scattered over various files.
  • The precedence of rules is directly apparent from the definition of the RuleTable.
  • Generic rules (e.g. the projection of a linear non-parametric Operator by simply applying the basis) can be easily scheduled to take precedence over more specific rules.
  • Users can implement or modify RuleTables without modification of the classes shipped with pyMOR.

The Reduction Process

The reduction process in pyMOR is handled by so called reductors which take arbitrary Discretizations and additional data (e.g. the reduced basis) to create reduced Discretizations. If proper offline/online decomposition is achieved by the reductor, the reduced Discretization will not store any high-dimensional data. Note that there is no inherent distinction between low- and high-dimensional Discretizations in pyMOR. The only difference lies in the different types of operators, the Discretization contains.

This observation is particularly apparent in the case of the classical reduced basis method: the operators and functionals of a given discrete problem are projected onto the reduced basis space whereas the structure of the problem (i.e. the type of Discretization containing the operators) stays the same. pyMOR reflects this fact by offering with GenericRBReductor a generic algorithm which can be used to RB-project any discretization available to pyMOR. It should be noted however that this reductor is only able to efficiently offline/online-decompose affinely Parameter-dependent linear problems. Non-linear problems or such with no affine Parameter dependence require additional techniques such as empirical interpolation.

If you want to further dive into the inner workings of pyMOR, we highly recommend to study the source code of GenericRBReductor and to step through calls of this method with a Python debugger, such as ipdb.

Environment Variables

pyMOR respects the following environment variables:

PYMOR_CACHE_DISABLE
If 1, disable caching globally, overriding calls to enable_caching. This is mainly useful for debugging. See pymor.core.cache for more details.
PYMOR_COLORS_DISABLE
If 1, disable coloring of logging output.
PYMOR_WITH_SPHINX
This variable is set to 1 during API documentation generation using sphinx.
PYMOR_DEFAULTS
If empty or NONE, do not load any defaults from file. Otherwise, a :-separated list of the paths to a Python scripts containing defaults.

Release Notes

pyMOR 0.5 (January 17, 2019)

After more than two years of development, we are proud to announce the release of pyMOR 0.5! Highlights of this release are support for Python 3, bindings for the NGSolve finite element library, new linear algebra algorithms, various VectorArray usability improvements, as well as a redesign of pyMOR’s projection algorithms based on RuleTables.

Especially we would like to highlight the addition of various system-theoretic reduction methods such as Balanced Truncation or IRKA. All algorithms are implemented in terms of pyMOR’s Operator and VectorArray interfaces, allowing their application to any model implemented using one of the PDE solver supported by pyMOR. In particular, no import of the system matrices is required.

Over 1,500 single commits have entered this release. For a full list of changes see here.

pyMOR 0.5 contains contributions by Linus Balicki, Julia Brunken and Christoph Lehrenfeld. See here for more details.

Release highlights

Python 3 support

pyMOR is now compatible with Python 3.5 or greater. Since the use of Python 3 is now standard in the scientific computing community and security updates for Python 2 will stop in less than a year (https://pythonclock.org), we decided to no longer support Python 2 and make pyMOR 0.5 a Python 3-only release. Switching to Python 3 also allows us to leverage newer language features such as the @ binary operator for concatenation of Operators, keyword-only arguments or improved support for asynchronous programming.

System-theoretic MOR methods

With 386 commits, [#464] added systems-theoretic methods to pyMOR. Module pymor.discretizations.iosys contains new discretization classes for input-output systems, e.g. LTISystem, SecondOrderSystem and TransferFunction. At present, methods related to these classes mainly focus on continuous-time, non-parametric systems.

Since matrix equation solvers are important tools in many system-theoretic methods, support for Lyapunov, Riccati and Sylvester equations has been added in pymor.algorithms.lyapunov, pymor.algorithms.riccati and pymor.algorithms.sylvester. A generic low-rank ADI (Alternating Direction Implicit) solver for Lyapunov equations is implemented in pymor.algorithms.lradi. Furthermore, bindings to low-rank and dense solvers for Lyapunov and Riccati equations from SciPy, Slycot and Py-M.E.S.S. are provided in pymor.bindings.scipy, pymor.bindings.slycot and pymor.bindings.pymess. A generic Schur decomposition-based solver for sparse-dense Sylvester equations is implemented in pymor.algorithms.sylvester.

Balancing Truncation (BT) and Iterative Rational Krylov Algorithm (IRKA) are implemented in BTReductor and IRKAReductor. LQG and Bounded Real variants of BT are also available (LQGBTReductor, BRBTReductor). Bitangential Hermite interpolation (used in IRKA) is implemented in LTI_BHIReductor. Two-Sided Iteration Algorithm (TSIA), a method related to IRKA, is implemented in TSIAReductor.

Several structure-preserving MOR methods for second-order systems have been implemented. Balancing-based MOR methods are implemented in pymor.reductors.sobt, bitangential Hermite interpolation in SO_BHIReductor and Second-Order Reduced IRKA (SOR-IRKA) in SOR_IRKAReductor.

For more general transfer functions, MOR methods which return LTISystems are also available. Bitangential Hermite interpolation is implemented in TFInterpReductor and Transfer Function IRKA (TF-IRKA) in TF_IRKAReductor.

Usage examples can be found in the heat and string_equation demo scripts.

NGSolve support

We now ship bindings for the NGSolve finite element library. Wrapper classes for VectorArrays and matrix-based Operators can be found in the pymor.bindings.ngsolve module. A usage example can be found in the thermalblock_simple demo script.

New linear algebra algorithms

pyMOR now includes an implementation of the HAPOD algorithm for fast distributed or incremental computation of the Proper Orthogonal Decomposition (pymor.algorithms.hapod). The code allows for arbitrary sub-POD trees, on-the-fly snapshot generation and shared memory parallelization via concurrent.futures. A basic usage example can be found in the hapod demo script.

In addition, the Gram-Schmidt biorthogonalization algorithm has been included in pymor.algorithms.gram_schmidt.

VectorArray improvements

VectorArrays in pyMOR have undergone several usability improvements:

  • The somewhat dubious concept of a subtype has been superseded by the concept of VectorSpaces which act as factories for VectorArrays. In particular, instead of a subtype, VectorSpaces can now hold meaningful attributes (e.g. the dimension) which are required to construct VectorArrays contained in the space. The id attribute allows to differentiate between technically identical but mathematically different spaces [#323].
  • VectorArrays can now be indexed to select a subset of vectors to operate on. In contrast to advanced indexing in NumPy, indexing a VectorArray will always return a view onto the original array data [#299].
  • New methods with clear semantics have been introduced for the conversion of VectorArrays to (to_numpy) and from (from_numpy) NumPy arrays [#446].
  • Inner products between VectorArrays w.r.t. to a given inner product Operator or their norm w.r.t. such an operator can now easily be computed by passing the Operator as the optional product argument to the new inner and norm methods [#407].
  • The components method of VectorArrays has been renamed to the more intuitive name dofs [#414].
  • The l2_norm2 and norm2 have been introduced to compute the squared vector norms [#237].
RuleTable based algorithms

In pyMOR 0.5, projection algorithms are implemented via recursively applied tables of transformation rules. This replaces the previous inheritance-based approach. In particular, the projected method to perform a (Petrov-)Galerkin projection of an arbitrary Operator has been removed and replaced by a free project function. Rule-based algorithms are implemented by deriving from the RuleTable base class [#367], [#408].

This approach has several advantages:

  • Rules can match based on the class of the object, but also on more general conditions, e.g. the name of the Operator or being linear and non-parametric.
  • The entire mathematical algorithm can be specified in a single file even when the definition of the possible classes the algorithm can be applied to is scattered over various files.
  • The precedence of rules is directly apparent from the definition of the RuleTable.
  • Generic rules (e.g. the projection of a linear non-parametric Operator by simply applying the basis) can be easily scheduled to take precedence over more specific rules.
  • Users can implement or modify RuleTables without modification of the classes shipped with pyMOR.

Additional new features

  • Reduction algorithms are now implemented using mutable reductor objects, e.g. GenericRBReductor, which store and extend the reduced bases onto which the model is projected. The only return value of the reductor’s reduce method is now the reduced discretization. Instead of a separate reconstructor, the reductor’s reconstruct method can be used to reconstruct a high-dimensional state-space representation. Additional reduction data (e.g. used to speed up repeated reductions in greedy algorithms) is now managed by the reductor [#375].

  • Linear combinations and concatenations of Operators can now easily be formed using arithmetic operators [#421].

  • The handling of complex numbers in pyMOR is now more consistent. See [#458], [#362], [#447] for details. As a consequence of these changes, the rhs Operator in StationaryDiscretization is now a vector-like Operator instead of a functional.

  • The analytical problems and discretizers of pyMOR’s discretization toolbox have been reorganized and improved. All problems are now implemented as instances of StationaryProblem or InstationaryProblem, which allows an easy exchange of data Functions of a predefined problem with user-defined Functions. Affine decomposition of Functions is now represented by specifying a LincombFunction as the respective data function [#312], [#316], [#318], [#337].

  • The pymor.core.config module allows simple run-time checking of the availability of optional dependencies and their versions [#339].

  • Packaging improvements

    A compiler toolchain is no longer necessary to install pyMOR as we are now distributing binary wheels for releases through the Python Package Index (PyPI). Using the extras_require mechanism the user can select to install either a minimal set:

    pip install pymor
    

    or almost all, including optional, dependencies:

    pip install pymor[full]
    

    A docker image containing all of the discretization packages pyMOR has bindings to is available for demonstration and development purposes:

    docker run -it pymor/demo:0.5 pymor-demo -h
    docker run -it pymor/demo:0.5 pymor-demo thermalblock --fenics 2 2 5 5
    

Backward incompatible changes

  • dim_outer has been removed from the grid interface [#277].
  • All wrapper code for interfacing with external PDE libraries or equation solvers has been moved to the pymor.bindings package. For instance, FenicsMatrixOperator can now be found in the pymor.bindings.fenics module. [#353]
  • The source and range arguments of the constructor of ZeroOperator have been swapped to comply with related function signatures [#415].
  • The identifiers discretization, rb_discretization, ei_discretization have been replaced by d, rd, ei_d throughout pyMOR [#416].
  • The _matrix attribute of NumpyMatrixOperator has been renamed to matrix [#436]. If matrix holds a NumPy array this array is automatically made read-only to prevent accidental modification of the Operator [#462].
  • The BoundaryType class has been removed in favor of simple strings [#305].
  • The complicated and unused mapping of local parameter component names to global names has been removed [#306].

Further notable improvements

pyMOR 0.4 (September 28, 2016)

With the pyMOR 0.4 release we have changed the copyright of pyMOR to

Copyright 2013-2016 pyMOR developers and contributors. All rights reserved.

Moreover, we have added a Contribution guideline to help new users with starting to contribute to pyMOR. Over 800 single commits have entered this release. For a full list of changes see here. pyMOR 0.4 contains contributions by Andreas Buhr, Michael Laier, Falk Meyer, Petar Mlinarić and Michael Schaefer. See here for more details.

Release highlights

FEniCS and deal.II support

pyMOR now includes wrapper classes for integrating PDE solvers written with the dolfin library of the FEniCS project. For a usage example, see pymordemos.thermalblock_simple.discretize_fenics. Experimental support for deal.II can be found in the pymor-deal.II repository of the pyMOR GitHub organization.

Parallelization of pyMOR’s reduction algorithms

We have added a parallelization framework to pyMOR which allows parallel execution of reduction algorithms based on a simple WorkerPool interface [#14]. The greedy [#155] and ei_greedy algorithms [#162] have been refactored to utilize this interface. Two WorkerPool implementations are shipped with pyMOR: IPythonPool utilizes the parallel computing features of IPython, allowing parallel algorithm execution in large heterogeneous clusters of computing nodes. MPIPool can be used to benefit from existing MPI-based parallel HPC computing architectures [#161].

Support classes for MPI distributed external PDE solvers

While pyMOR’s VectorArray, Operator and Discretization interfaces are agnostic to the concrete (parallel) implementation of the corresponding objects in the PDE solver, external solvers are often integrated by creating wrapper classes directly corresponding to the solvers data structures. However, when the solver is executed in an MPI distributed context, these wrapper classes will then only correspond to the rank-local data of a distributed VectorArray or Operator.

To facilitate the integration of MPI parallel solvers, we have added MPI helper classes [#163] in pymor.vectorarrays.mpi, pymor.operators.mpi and pymor.discretizations.mpi that allow an automatic wrapping of existing sequential bindings for MPI distributed use. These wrapper classes are based on a simple event loop provided by pymor.tools.mpi, which is used in the interface methods of the wrapper classes to dispatch into MPI distributed execution of the corresponding methods on the underlying MPI distributed objects.

The resulting objects can be used on MPI rank 0 (including interactive Python sessions) without any further changes to pyMOR or the user code. For an example, see pymordemos.thermalblock_simple.discretize_fenics.

New reduction algorithms
  • adaptive_greedy uses adaptive parameter training set refinement according to [HDO11] to prevent overfitting of the reduced model to the training set [#213].
  • reduce_parabolic reduces linear parabolic problems using reduce_generic_rb and assembles an error estimator similar to [GP05], [HO08]. The parabolic_mor demo contains a simple sample application using this reductor [#190].
  • The estimate_image and estimate_image_hierarchical algorithms can be used to find an as small as possible space in which the images of a given list of operators for a given source space are contained for all possible parameters mu. For possible applications, see reduce_residual which now uses estimate_image_hierarchical for Petrov-Galerkin projection of the residual operator [#223].
Copy-on-write semantics for VectorArrays

The copy method of the VectorArray interface is now assumed to have copy-on-write semantics. I.e., the returned VectorArray will contain a reference to the same data as the original array, and the actual data will only be copied when one of the arrays is changed. Both NumpyVectorArray and ListVectorArray have been updated accordingly [#55]. As a main benefit of this approach, immutable objects having a VectorArray as an attribute now can safely create copies of the passed VectorArrays (to ensure the immutability of their state) without having to worry about unnecessarily increased memory consumption.

Improvements to pyMOR’s discretizaion tookit
  • An unstructured triangular Grid is now provided by UnstructuredTriangleGrid. Such a Grid can be obtained using the discretize_gmsh method, which can parse Gmsh output files. Moreover, this method can generate Gmsh input files to create unstructured meshes for an arbitrary PolygonalDomain [#9].
  • Basic support for parabolic problems has been added. The discretize_parabolic_cg and discretize_parabolic_fv methods can be used to build continuous finite element or finite volume Discretizations from a given pymor.analyticalproblems.parabolic.ParabolicProblem. The parabolic demo demonstrates the use of these methods [#189].
  • The pymor.discretizers.disk module contains methods to create stationary and instationary affinely decomposed Discretizations from matrix data files and an .ini file defining the given problem.
  • EllipticProblems can now also contain advection and reaction terms in addition to the diffusion part. discretize_elliptic_cg has been extended accordingly [#211].
  • The continuous Galerkin module has been extended to support Robin boundary conditions [#110].
  • BitmapFunction allows to use grayscale image data as data Functions [#194].
  • For the visualization of time-dependent data, the colorbars can now be rescaled with each new frame [#91].
Caching improvements
  • state id generation is now based on deterministic pickling. In previous version of pyMOR, the state id of immutable objects was computed from the state ids of the parameters passed to the object’s __init__ method. This approach was complicated and error-prone. Instead, we now compute the state id as a hash of a deterministic serialization of the object’s state. While this approach is more robust, it is also slightly more expensive. However, due to the object’s immutability, the state id only has to be computed once, and state ids are now only required for storing results in persistent cache regions (see below). Computing such results will usually be much more expensive than the state id calculation [#106].
  • CacheRegions now have a persistent attribute indicating whether the cache data will be kept between program runs. For persistent cache regions the state id of the object for which the cached method is called has to be computed to obtain a unique persistent id for the given object. For non-persistent regions the object’s uid can be used instead. pymor.core.cache_regions now by default contains 'memory', 'disk' and 'persistent' cache regions [#182], [#121] .
  • defaults can now be marked to not affect state id computation. In previous version of pyMOR, changing any default value caused a change of the state id pyMOR’s defaults dictionary, leading to cache misses. While this in general is desirable, as, for instance, changed linear solver default error tolerances might lead to different solutions for the same Discretization object, it is clear for many I/O related defaults, that these will not affect the outcome of any computation. For these defaults, the defaults decorator now accepts a sid_ignore parameter, to exclude these defaults from state id computation, preventing changes of these defaults causing cache misses [#81].
  • As an alternative to using the @cached decorator, cached_method_call can be used to cache the results of a function call. This is now used in solve to enable parsing of the input parameter before it enters the cache key calculation [#231].

Additional new features

Backward incompatible changes

pyMOR 0.3 (March 2, 2015)

  • Introduction of the vector space concept for even simpler integration with external solvers.
  • Addition of a generic Newton algorithm.
  • Support for Jacobian evaluation of empirically interpolated operators.
  • Greatly improved performance of the EI-Greedy algorithm. Addition of the DEIM algorithm.
  • A new algorithm for residual operator projection and a new, numerically stable a posteriori error estimator for stationary coercive problems based on this algorithm. (cf. A. Buhr, C. Engwer, M. Ohlberger, S. Rave, ‘A numerically stable a posteriori error estimator for reduced basis approximations of elliptic equations’, proceedings of WCCM 2014, Barcelona, 2014.)
  • A new, easy to use mechanism for setting and accessing default values.
  • Serialization via the pickle module is now possible for each class in pyMOR. (See the new ‘analyze_pickle’ demo.)
  • Addition of generic iterative linear solvers which can be used in conjunction with any operator satisfying pyMOR’s operator interface. Support for least squares solvers and PyAMG (http://www.pyamg.org/).
  • An improved SQLite-based cache backend.
  • Improvements to the built-in discretizations: support for bilinear finite elements and addition of a finite volume diffusion operator.
  • Test coverage has been raised from 46% to 75%.

Over 500 single commits have entered this release. A full list of all changes can be obtained under the following address: https://github.com/pymor/pymor/compare/0.2.2…0.3.0

Bibliography

[A05]A. C. Antoulas, Approximation of Large-Scale Dynamical Systems, SIAM, 2005.
[ABG10]A. C. Antoulas, C. A. Beattie, S. Gugercin, Interpolatory model reduction of large-scale dynamical systems, Efficient Modeling and Control of Large-Scale Systems, Springer-Verlag, 2010.
[BG09]C. A. Beattie, S. Gugercin, Interpolatory projection methods for structure-preserving model reduction, Systems & Control Letters 58, 2009
[BG12]C. A. Beattie, S. Gugercin, Realization-independent H2-approximation, Proceedings of the 51st IEEE Conference on Decision and Control, 2012.
[BKS11]P. Benner, M. Köhler, J. Saak, Sparse-Dense Sylvester Equations in \mathcal{H}_2-Model Order Reduction, Max Planck Institute Magdeburg Preprint, available from http://www.mpi-magdeburg.mpg.de/preprints/, 2011.
[BEOR14]A. Buhr, C. Engwer, M. Ohlberger, S. Rave, A Numerically Stable A Posteriori Error Estimator for Reduced Basis Approximations of Elliptic Equations, Proceedings of the 11th World Congress on Computational Mechanics, 2014.
[CLVV06]Y. Chahlaoui, D. Lemonnier, A. Vandendorpe, P. Van Dooren, Second-order balanced truncation, Linear Algebra and its Applications, 2006, 415(2–3), 373-384
[GP05]M. A. Grepl, A. T. Patera, A Posteriori Error Bounds For Reduced-Basis Approximations Of Parametrized Parabolic Partial Differential Equations, M2AN 39(1), 157-181, 2005.
[GAB08]S. Gugercin, A. C. Antoulas, C. A. Beattie, \mathcal{H}_2 model reduction for large-scale linear dynamical systems, SIAM Journal on Matrix Analysis and Applications, 30(2), 609-638, 2008.
[HDO11]Haasdonk, B.; Dihlmann, M. & Ohlberger, M., A training set and multiple bases generation approach for parameterized model reduction based on adaptive grids in parameter space, Math. Comput. Model. Dyn. Syst., 2011, 17, 423-442
[HO08]B. Haasdonk, M. Ohlberger, Reduced basis method for finite volume approximations of parametrized evolution equations, M2AN 42(2), 277-302, 2008.
[HLR18]C. Himpe, T. Leibner, S. Rave, Hierarchical Approximate Proper Orthogonal Decomposition, SIAM J. Sci. Comput. 40, A3267-A3292, 2018.
[PK16]P. Kürschner, Efficient Low-Rank Solution of Large-Scale Matrix Equations, Shaker Verlag Aachen, available from http://pubman.mpdl.mpg.de/pubman/, 2016.
[MS96]D. G. Meyer and S. Srinivasan, Balancing and model reduction for second-order form linear systems, IEEE Trans. Automat. Control, 1996, 41, 1632–1644
[MG91]D. Mustafa, K. Glover, Controller Reduction by \mathcal{H}_\infty-Balanced Truncation, IEEE Transactions on Automatic Control, 36(6), 668-682, 1991.
[OJ88]P. C. Opdenacker, E. A. Jonckheere, A Contraction Mapping Preserving Balanced Reduction Scheme and Its Infinity Norm Error Bounds, IEEE Transactions on Circuits and Systems, 35(2), 184-189, 1988.
[RS08]T. Reis and T. Stykel, Balanced truncation model reduction of second-order systems, Math. Comput. Model. Dyn. Syst., 2008, 14(5), 391-406
[W12]S. Wyatt, Issues in Interpolatory Model Reduction: Inexact Solves, Second Order Systems and DAEs, PhD thesis, Virginia Tech, 2012
[XZ11]Y. Xu and T. Zeng, Optimal \mathcal{H}_2 Model Reduction for Large Scale MIMO Systems via Tangential Interpolation, International Journal of Numerical Analysis and Modeling, vol. 8, no. 1, pp. 174-188, 2011

API Documentation

pymor package

Subpackages

pymor.algorithms package
Submodules
adaptivegreedy module
class pymor.algorithms.adaptivegreedy.AdaptiveSampleSet(parameter_space)[source]

Bases: pymor.core.interfaces.BasicInterface

An adaptive parameter sample set.

Used by adaptive_greedy.


pymor.algorithms.adaptivegreedy._estimate(mu, rd=None, d=None, reductor=None, error_norm=None)[source]

Called by adaptive_greedy.


pymor.algorithms.adaptivegreedy.adaptive_greedy(d, reductor, parameter_space=None, use_estimator=True, error_norm=None, target_error=None, max_extensions=None, validation_mus=0, rho=1.1, gamma=0.2, theta=0.0, extension_params=None, visualize=False, visualize_vertex_size=80, pool=<pymor.parallel.dummy.DummyPool object>)[source]

Greedy basis generation algorithm with adaptively refined training set.

This method extends pyMOR’s default greedy greedy basis generation algorithm by adaptive refinement of the parameter training set according to [HDO11] to prevent overfitting of the reduced basis to the training set. This is achieved by estimating the reduction error on an additional validation set of parameters. If the ratio between the estimated errors on the validation set and the validation set is larger than rho, the training set is refined using standard grid refinement techniques.

Parameters

d
See greedy.
reductor
See greedy.
parameter_space
The ParameterSpace for which to compute the reduced model. If None, the parameter space of d is used.
use_estimator
See greedy.
error_norm
See greedy.
target_error
See greedy.
max_extensions
See greedy.
validation_mus
One of the following:
  • a list of Parameters to use as validation set,
  • a positive number indicating the number of random parameters to use as validation set,
  • a non-positive number, indicating the negative number of random parameters to use as validation set in addition to the centers of the elements of the adaptive training set.
rho
Maximum allowed ratio between maximum estimated error on validation set vs. maximum estimated error on training set. If the ratio is larger, the training set is refined.
gamma
Weight of the age penalty term in the training set refinement indicators.
theta
Ratio of training set elements to select for refinement. (One element is always refined.)
extension_params
See greedy.
visualize
If True, visualize the refinement indicators. (Only available for 2 and 3 dimensional parameter spaces.)
visualize_vertex_size
Size of the vertices in the visualization.
pool
See greedy.

Returns

Dict with the following fields

rd:The reduced Discretization obtained for the computed basis.
extensions:Number of greedy iterations.
max_errs:Sequence of maximum errors during the greedy run.
max_err_mus:The parameters corresponding to max_errs.
max_val_errs:Sequence of maximum errors on the validation set.
max_val_err_mus:The parameters corresponding to max_val_errs.
refinements:Number of refinements made in each extension step.
training_set_sizes:The final size of the training set in each extension step.
time:Duration of the algorithm.
reduction_data:Reduction data returned by the last reductor call.
arnoldi module
pymor.algorithms.arnoldi.arnoldi(A, E, b, sigma, trans=False)[source]

Rational Arnoldi algorithm.

If trans == False, using Arnoldi process, computes a real orthonormal basis for the rational Krylov subspace

\mathrm{span}\{(\sigma_1 E - A)^{-1} b, (\sigma_2 E - A)^{-1} b, \ldots,
(\sigma_r E - A)^{-1} b\},

otherwise, computes the same for

\mathrm{span}\{(\sigma_1 E - A)^{-T} b^T, (\sigma_2 E - A)^{-T} b^T,
\ldots, (\sigma_r E - A)^{-T} b^T\}.

Interpolation points in sigma are allowed to repeat (in any order). Then, in the above expression,

\underbrace{(\sigma_i E - A)^{-1} b, \ldots,
(\sigma_i E - A)^{-1} b}_{m \text{ times}}

is replaced by

(\sigma_i E - A)^{-1} b, (\sigma_i E - A)^{-2} b, \ldots,
(\sigma_i E - A)^{-m} b.

Analogously for the trans == True case.

Parameters

A
Real Operator A.
E
Real Operator E.
b
Real vector-like operator (if trans is False) or functional (if trans is True).
sigma
Interpolation points (closed under conjugation).
trans
Boolean, see above.

Returns

V
Projection matrix.
basic module

Module containing some basic but generic linear algebra algorithms.


pymor.algorithms.basic.almost_equal(U, V, product=None, norm=None, rtol=1e-14, atol=1e-14)[source]

Compare U and V for almost equality.

The vectors of U and V are compared in pairs for almost equality. Two vectors u and v are considered almost equal iff

||u - v|| <= atol + ||v|| * rtol.

The norm to be used can be specified via the norm or product parameter.

If the length of U resp. V is 1, the single specified vector is compared to all vectors of the other array. Otherwise, the lengths of both indexed arrays have to agree.

Parameters

U, V
VectorArrays to be compared.
product
If specified, use this inner product Operator to compute the norm. product and norm are mutually exclusive.
norm
If specified, must be a callable which is used to compute the norm or, alternatively, one of the strings ‘l1’, ‘l2’, ‘sup’, in which case the respective VectorArray norm methods are used. product and norm are mutually exclusive. If neither is specified, norm='l2' is assumed.
rtol
The relative tolerance.
atol
The absolute tolerance.

Defaults

rtol, atol (see pymor.core.defaults)


pymor.algorithms.basic.project_array(U, basis, product=None, orthonormal=True)[source]

Orthogonal projection of VectorArray onto subspace.

Parameters

U
The VectorArray to project.
basis
VectorArray of basis vectors for the subspace onto which to project.
product
Inner product Operator w.r.t. which to project.
orthonormal
If True, the vectors in basis are assumed to be orthonormal w.r.t. product.

Returns

The projected VectorArray.


pymor.algorithms.basic.relative_error(U, V, product=None)[source]

Compute error between U and V relative to norm of U.

ei module

This module contains algorithms for the empirical interpolation of Operators.

The main work for generating the necessary interpolation data is handled by the ei_greedy method. The objects returned by this method can be used to instantiate an EmpiricalInterpolatedOperator.

As a convenience, the interpolate_operators method allows to perform the empirical interpolation of the Operators of a given discretization with a single function call.


pymor.algorithms.ei.deim(U, modes=None, atol=None, rtol=None, product=None, pod_options={})[source]

Generate data for empirical interpolation using DEIM algorithm.

Given a VectorArray U, this method generates a collateral basis and interpolation DOFs for empirical interpolation of the vectors contained in U. The returned objects can be used to instantiate an EmpiricalInterpolatedOperator (with triangular=False).

The collateral basis is determined by the first pod modes of U.

Parameters

U
A VectorArray of vectors to interpolate.
modes
Dimension of the collateral basis i.e. number of POD modes of the vectors in U.
atol
Absolute POD tolerance.
rtol
Relative POD tolerance.
product
Inner product Operator used for the POD.
pod_options
Dictionary of additional options to pass to the pod algorithm.

Returns

interpolation_dofs
NumPy array of the DOFs at which the vectors are interpolated.
collateral_basis
VectorArray containing the generated collateral basis.
data

Dict containing the following fields:

svals:POD singular values.

pymor.algorithms.ei.ei_greedy(U, error_norm=None, atol=None, rtol=None, max_interpolation_dofs=None, copy=True, pool=<pymor.parallel.dummy.DummyPool object>)[source]

Generate data for empirical interpolation using EI-Greedy algorithm.

Given a VectorArray U, this method generates a collateral basis and interpolation DOFs for empirical interpolation of the vectors contained in U. The returned objects can be used to instantiate an EmpiricalInterpolatedOperator (with triangular=True).

The interpolation data is generated by a greedy search algorithm, where in each loop iteration the worst approximated vector in U is added to the collateral basis.

Parameters

U
A VectorArray of vectors to interpolate.
error_norm
Norm w.r.t. which to calculate the interpolation error. If None, the Euclidean norm is used.
atol
Stop the greedy search if the largest approximation error is below this threshold.
rtol
Stop the greedy search if the largest relative approximation error is below this threshold.
max_interpolation_dofs
Stop the greedy search if the number of interpolation DOF (= dimension of the collateral basis) reaches this value.
copy
If False, U will be modified during executing of the algorithm.
pool
If not None, the WorkerPool to use for parallelization.

Returns

interpolation_dofs
NumPy array of the DOFs at which the vectors are evaluated.
collateral_basis
VectorArray containing the generated collateral basis.
data

Dict containing the following fields:

errors:Sequence of maximum approximation errors during greedy search.
triangularity_errors:Sequence of maximum absolute values of interoplation matrix coefficients in the upper triangle (should be near zero).

pymor.algorithms.ei.interpolate_operators(d, operator_names, parameter_sample, error_norm=None, product=None, atol=None, rtol=None, max_interpolation_dofs=None, pod_options={}, alg='ei_greedy', pool=<pymor.parallel.dummy.DummyPool object>)[source]

Empirical operator interpolation using the EI-Greedy/DEIM algorithm.

This is a convenience method to facilitate the use of ei_greedy or deim. Given a Discretization, names of Operators, and a sample of Parameters, first the operators are evaluated on the solution snapshots of the discretization for the provided parameters. These evaluations are then used as input for ei_greedy/deim. Finally the resulting interpolation data is used to create EmpiricalInterpolatedOperators and a new discretization with the interpolated operators is returned.

Note that this implementation creates one common collateral basis for all specified operators, which might not be what you want.

Parameters

d
The Discretization whose Operators will be interpolated.
operator_names
List of keys in the operators dict of the discretization. The corresponding Operators will be interpolated.
parameter_sample
A list of Parameters for which solution snapshots are calculated.
error_norm
See ei_greedy. Has no effect if alg == 'deim'.
product
Inner product for POD computation in deim. Has no effect if alg == 'ei_greedy'.
atol
See ei_greedy.
rtol
See ei_greedy.
max_interpolation_dofs
See ei_greedy.
pod_options
Further options for pod algorithm. Has no effect if alg == 'ei_greedy'.
alg
Either ei_greedy or deim.
pool
If not None, the WorkerPool to use for parallelization.

Returns

ei_d
Discretization with Operators given by operator_names replaced by EmpiricalInterpolatedOperators.
data

Dict containing the following fields:

dofs:NumPy array of the DOFs at which the Operators have to be evaluated.
basis:VectorArray containing the generated collateral basis.

In addition, data contains the fields of the data dict returned by ei_greedy/deim.

error module
pymor.algorithms.error.reduction_error_analysis(rd, d, reductor, test_mus=10, basis_sizes=0, random_seed=None, estimator=True, condition=False, error_norms=(), error_norm_names=None, estimator_norm_index=0, custom=(), plot=False, plot_custom_logarithmic=True, pool=<pymor.parallel.dummy.DummyPool object>)[source]

Analyze the model reduction error.

The maximum model reduction error is estimated by solving the reduced Discretization for given random Parameters.

Parameters

rd
The reduced Discretization.
d
The high-dimensional Discretization.
reductor
The reductor which has created rd.
test_mus
Either a list of Parameters to compute the errors for, or the number of parameters which are sampled randomly from parameter_space (if given) or rd.parameter_space.
basis_sizes
Either a list of reduced basis dimensions to consider, or the number of dimensions (which are then selected equidistantly, always including the maximum reduced space dimension). The dimensions are input for the dim-Parameter of reductor.reduce().
random_seed
If test_mus is a number, use this value as random seed for drawing the Parameters.
estimator
If True evaluate the error estimator of rd on the test Parameters.
condition
If True, compute the condition of the reduced system matrix for the given test Parameters (can only be specified if rd is an instance of StationaryDiscretization and rd.operator is linear).
error_norms
List of norms in which to compute the model reduction error.
error_norm_names
Names of the norms given by error_norms. If None, the name attributes of the given norms are used.
estimator_norm_index
When estimator is True and error_norms are specified, this is the index of the norm in error_norms w.r.t. which to compute the effectivity of the estimator.
custom

List of custom functions which are evaluated for each test Parameter and basis size. The functions must have the signature

def custom_value(rd, d, reductor, mu, dim):
    pass
plot
If True, generate a plot of the computed quantities w.r.t. the basis size.
plot_custom_logarithmic
If True, use a logarithmic y-axis to plot the computed custom values.
pool
If not None, the WorkerPool to use for parallelization.

Returns

Dict with the following fields

mus:The test Parameters which have been considered.
basis_sizes:The reduced basis dimensions which have been considered.
norms:NumPy array of the norms of the high-dimensional solutions w.r.t. all given test Parameters, reduced basis dimensions and norms in error_norms. (Only present when error_norms has been specified.)
max_norms:Maxima of norms over the given test Parameters.
max_norm_mus:Parameters corresponding to max_norms.
errors:NumPy array of the norms of the model reduction errors w.r.t. all given test Parameters, reduced basis dimensions and norms in error_norms. (Only present when error_norms has been specified.)
max_errors:Maxima of errors over the given test Parameters.
max_error_mus:Parameters corresponding to max_errors.
rel_errors:errors divided by norms. (Only present when error_norms has been specified.)
max_rel_errors:Maxima of rel_errors over the given test Parameters.
max_rel_error_mus:Parameters corresponding to max_rel_errors.
error_norm_names:Names of the given error_norms. (Only present when error_norms has been specified.)
estimates:NumPy array of the model reduction error estimates w.r.t. all given test Parameters and reduced basis dimensions. (Only present when estimator is True.)
max_estimate:Maxima of estimates over the given test Parameters.
max_estimate_mus:Parameters corresponding to max_estimates.
effectivities:errors divided by estimates. (Only present when estimator is True and error_norms has been specified.)
min_effectivities:Minima of effectivities over the given test Parameters.
min_effectivity_mus:Parameters corresponding to min_effectivities.
max_effectivities:Maxima of effectivities over the given test Parameters.
max_effectivity_mus:Parameters corresponding to max_effectivities.
errors:NumPy array of the reduced system matrix conditions w.r.t. all given test Parameters and reduced basis dimensions. (Only present when conditions is True.)
max_conditions:Maxima of conditions over the given test Parameters.
max_condition_mus:Parameters corresponding to max_conditions.
custom_values:NumPy array of custom function evaluations w.r.t. all given test Parameters, reduced basis dimensions and functions in custom. (Only present when custom has been specified.)
max_custom_values:Maxima of custom_values over the given test Parameters.
max_custom_values_mus:Parameters corresponding to max_custom_values.
time:Time (in seconds) needed for the error analysis.
summary:String containing a summary of all computed quantities for the largest (last) considered basis size.
figure:The figure containing the generated plots. (Only present when plot is True.)
genericsolvers module

This module contains some iterative linear solvers which only use the Operator interface


pymor.algorithms.genericsolvers.apply_inverse(op, rhs, options=None, least_squares=False, check_finite=True, default_solver='generic_lgmres', default_least_squares_solver='generic_least_squares_lsmr')[source]

Solve linear equation system.

Applies the inverse of op to the vectors in rhs using a generic iterative solver.

Parameters

op
The linear, non-parametric Operator to invert.
rhs
VectorArray of right-hand sides for the equation system.
options
The solver_options to use (see solver_options).
least_squares
If True, return least squares solution.
check_finite
Test if solution only contains finite values.
default_solver
Default solver to use (generic_lgmres, generic_least_squares_lsmr, generic_least_squares_lsqr).
default_least_squares_solver
Default solver to use for least squares problems (generic_least_squares_lsmr, generic_least_squares_lsqr).

Returns

VectorArray of the solution vectors.

Defaults

check_finite, default_solver, default_least_squares_solver (see pymor.core.defaults)


pymor.algorithms.genericsolvers.lgmres(A, b, x0=None, tol=1e-05, maxiter=1000, M=None, callback=None, inner_m=30, outer_k=3, outer_v=None, store_outer_Av=True)[source]

pymor.algorithms.genericsolvers.lsmr(A, b, damp=0.0, atol=1e-06, btol=1e-06, conlim=100000000.0, maxiter=None, show=False)[source]

pymor.algorithms.genericsolvers.lsqr(A, b, damp=0.0, atol=1e-08, btol=1e-08, conlim=100000000.0, iter_lim=None, show=False)[source]

pymor.algorithms.genericsolvers.solver_options(lgmres_tol=1e-05, lgmres_maxiter=1000, lgmres_inner_m=39, lgmres_outer_k=3, least_squares_lsmr_damp=0.0, least_squares_lsmr_atol=1e-06, least_squares_lsmr_btol=1e-06, least_squares_lsmr_conlim=100000000.0, least_squares_lsmr_maxiter=None, least_squares_lsmr_show=False, least_squares_lsqr_damp=0.0, least_squares_lsqr_atol=1e-06, least_squares_lsqr_btol=1e-06, least_squares_lsqr_conlim=100000000.0, least_squares_lsqr_iter_lim=None, least_squares_lsqr_show=False)[source]

Returns available solvers with default solver_options.

Parameters

lgmres_tol
See scipy.sparse.linalg.lgmres.
lgmres_maxiter
See scipy.sparse.linalg.lgmres.
lgmres_inner_m
See scipy.sparse.linalg.lgmres.
lgmres_outer_k
See scipy.sparse.linalg.lgmres.
least_squares_lsmr_damp
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_atol
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_btol
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_conlim
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_maxiter
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_show
See scipy.sparse.linalg.lsmr.
least_squares_lsqr_damp
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_atol
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_btol
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_conlim
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_iter_lim
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_show
See scipy.sparse.linalg.lsqr.

Returns

A dict of available solvers with default solver_options.

Defaults

lgmres_tol, lgmres_maxiter, lgmres_inner_m, lgmres_outer_k, least_squares_lsmr_damp, least_squares_lsmr_atol, least_squares_lsmr_btol, least_squares_lsmr_conlim, least_squares_lsmr_maxiter, least_squares_lsmr_show, least_squares_lsqr_atol, least_squares_lsqr_btol, least_squares_lsqr_conlim, least_squares_lsqr_iter_lim, least_squares_lsqr_show (see pymor.core.defaults)

gram_schmidt module
pymor.algorithms.gram_schmidt.gram_schmidt(A, product=None, atol=1e-13, rtol=1e-13, offset=0, reiterate=True, reiteration_threshold=0.1, check=True, check_tol=0.001, copy=True)[source]

Orthonormalize a VectorArray using the stabilized Gram-Schmidt algorithm.

Parameters

A
The VectorArray which is to be orthonormalized.
product
The inner product Operator w.r.t. which to orthonormalize. If None, the Euclidean product is used.
atol
Vectors of norm smaller than atol are removed from the array.
rtol
Relative tolerance used to detect linear dependent vectors (which are then removed from the array).
offset
Assume that the first offset vectors are already orthonormal and start the algorithm at the offset + 1-th vector.
reiterate
If True, orthonormalize again if the norm of the orthogonalized vector is much smaller than the norm of the original vector.
reiteration_threshold
If reiterate is True, re-orthonormalize if the ratio between the norms of the orthogonalized vector and the original vector is smaller than this value.
check
If True, check if the resulting VectorArray is really orthonormal.
check_tol
Tolerance for the check.
copy
If True, create a copy of A instead of modifying A in-place.

Returns

The orthonormalized VectorArray.

Defaults

atol, rtol, reiterate, reiteration_threshold, check, check_tol (see pymor.core.defaults)


pymor.algorithms.gram_schmidt.gram_schmidt_biorth(V, W, product=None, reiterate=True, reiteration_threshold=0.1, check=True, check_tol=0.001, copy=True)[source]

Biorthonormalize a pair of VectorArrays using the biorthonormal Gram-Schmidt process.

See Algorithm 1 in [BKS11].

Parameters

V, W
The VectorArrays which are to be biorthonormalized.
product
The inner product Operator w.r.t. which to biorthonormalize. If None, the Euclidean product is used.
reiterate
If True, orthonormalize again if the norm of the orthogonalized vector is much smaller than the norm of the original vector.
reiteration_threshold
If reiterate is True, re-orthonormalize if the ratio between the norms of the orthogonalized vector and the original vector is smaller than this value.
check
If True, check if the resulting VectorArray is really orthonormal.
check_tol
Tolerance for the check.
copy
If True, create a copy of V and W instead of modifying V and W in-place.

Returns

The biorthonormalized VectorArrays.

greedy module
pymor.algorithms.greedy.greedy(d, reductor, samples, use_estimator=True, error_norm=None, atol=None, rtol=None, max_extensions=None, extension_params=None, pool=None)[source]

Greedy basis generation algorithm.

This algorithm generates a reduced basis by iteratively adding the worst approximated solution snapshot for a given training set to the reduced basis. The approximation error is computed either by directly comparing the reduced solution to the detailed solution or by using an error estimator (use_estimator == True). The reduction and basis extension steps are performed by calling the methods provided by the reductor and extension_algorithm arguments.

Parameters

d
The Discretization to reduce.
reductor
Reductor for reducing the given Discretization. This has to be an object with a reduce method, such that reductor.reduce() yields the reduced discretization, and an exted_basis method, such that reductor.extend_basis(U, copy_U=False, **extension_params) extends the current reduced basis by the vectors contained in U. For an example see CoerciveRBReductor.
samples
The set of Parameter samples on which to perform the greedy search.
use_estimator
If True, use rd.estimate() to estimate the errors on the sample set. Otherwise d.solve() is called to compute the exact model reduction error.
error_norm
If use_estimator == False, use this function to calculate the norm of the error. If None, the Euclidean norm is used.
atol
If not None, stop the algorithm if the maximum (estimated) error on the sample set drops below this value.
rtol
If not None, stop the algorithm if the maximum (estimated) relative error on the sample set drops below this value.
max_extensions
If not None, stop the algorithm after max_extensions extension steps.
extension_params
dict of parameters passed to the reductor.extend_basis method.
pool
If not None, the WorkerPool to use for parallelization.

Returns

Dict with the following fields

rd:The reduced Discretization obtained for the computed basis.
max_errs:Sequence of maximum errors during the greedy run.
max_err_mus:The parameters corresponding to max_errs.
extensions:Number of performed basis extensions.
time:Total runtime of the algorithm.
hapod module
class pymor.algorithms.hapod.DistHAPODTree(slices)[source]

Bases: pymor.algorithms.hapod.Tree

Attributes

Tree depth, root
BasicInterface logger, logging_disabled, name, uid

class pymor.algorithms.hapod.FakeExecutor[source]

Bases: object

Methods

FakeExecutor submit

class pymor.algorithms.hapod.IncHAPODTree(steps)[source]

Bases: pymor.algorithms.hapod.Tree

Attributes

Tree depth, root
BasicInterface logger, logging_disabled, name, uid

class pymor.algorithms.hapod.LifoExecutor(executor, max_workers=None)[source]

Bases: object

Methods

LifoExecutor done_callback, run_task, submit

class pymor.algorithms.hapod.Tree[source]

Bases: pymor.core.interfaces.BasicInterface

A rooted tree.

Attributes

Tree depth, root
BasicInterface logger, logging_disabled, name, uid

pymor.algorithms.hapod.default_pod_method(U, eps, is_root_node, product)[source]

pymor.algorithms.hapod.dist_hapod(num_slices, snapshots, eps, omega, product=None, executor=None, eval_snapshots_in_executor=False)[source]

Distributed Hierarchical Approximate POD.

This computes the distributed HAPOD from [HLR18].

Parameters

num_slices
The number of snapshot vector slices.
snapshots
A mapping snapshots(slice) returning for each slice number the associated snapshot vectors.
eps
Desired l2-mean approximation error.
omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
product
Inner product Operator w.r.t. which to compute the POD.
executor
If not None, a concurrent.futures.Executor object to use for parallelization.
eval_snapshots_in_executor
If True also parallelize the evaluation of the snapshot map.

Returns

modes
The computed POD modes.
svals
The associated singular values.
snap_count
The total number of input snapshot vectors.

pymor.algorithms.hapod.dist_vectorarray_hapod(num_slices, U, eps, omega, product=None, executor=None)[source]

Distributed Hierarchical Approximate POD.

This computes the distributed HAPOD from [HLR18] of a given VectorArray.

Parameters

num_slices
The number of snapshot vector slices.
U
The VectorArray of which to compute the HAPOD.
eps
Desired l2-mean approximation error.
omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
product
Inner product Operator w.r.t. which to compute the POD.
executor
If not None, a concurrent.futures.Executor object to use for parallelization.

Returns

modes
The computed POD modes.
svals
The associated singular values.
snap_count
The total number of input snapshot vectors.

pymor.algorithms.hapod.hapod(tree, snapshots, local_eps, product=None, pod_method=<function default_pod_method>, executor=None, eval_snapshots_in_executor=False)[source]

Compute the Hierarchical Approximate POD.

This is an implementation of the HAPOD algorithm from [HLR18].

Parameters

tree
A Tree defining the worker topology.
snapshots
A mapping snapshots(node) returning for each leaf node the associated snapshot vectors.
local_eps
A mapping local_eps(node, snap_count, num_vecs) assigning to each tree node node an l2 truncation error tolerance for the local pod based on the number of input vectors num_vecs and the total number of snapshot vectors below the given node snap_count.
product
Inner product Operator w.r.t. which to compute the POD.
pod_method
A function pod_method(U, eps, root_node, product) for computing the POD of the VectorArray U w.r.t. the given inner product product and the l2 error tolerance eps. root_node is set to True when the POD is computed at the root of the tree.
executor
If not None, a concurrent.futures.Executor object to use for parallelization.
eval_snapshots_in_executor
If True also parallelize the evaluation of the snapshot map.

Returns

modes
The computed POD modes.
svals
The associated singular values.
snap_count
The total number of input snapshot vectors.

pymor.algorithms.hapod.inc_hapod(steps, snapshots, eps, omega, product=None, executor=None, eval_snapshots_in_executor=False)[source]

Incremental Hierarchical Approximate POD.

This computes the incremental HAPOD from [HLR18].

Parameters

steps
The number of incremental POD updates.
snapshots
A mapping snapshots(step) returning for each incremental POD step the associated snapshot vectors.
eps
Desired l2-mean approximation error.
omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
product
Inner product Operator w.r.t. which to compute the POD.
executor
If not None, a concurrent.futures.Executor object to use for parallelization.
eval_snapshots_in_executor
If True also parallelize the evaluation of the snapshot map.

Returns

modes
The computed POD modes.
svals
The associated singular values.
snap_count
The total number of input snapshot vectors.

pymor.algorithms.hapod.inc_vectorarray_hapod(steps, U, eps, omega, product=None, executor=None)[source]

Incremental Hierarchical Approximate POD.

This computes the incremental HAPOD from [HLR18] for a given VectorArray.

Parameters

steps
The number of incremental POD updates.
U
The VectorArray of which to compute the HAPOD.
eps
Desired l2-mean approximation error.
omega
Tuning parameter (0 < omega < 1) to balance performance with approximation quality.
product
Inner product Operator w.r.t. which to compute the POD.
executor
If not None, a concurrent.futures.Executor object to use for parallelization.
eval_snapshots_in_executor
If True also parallelize the evaluation of the snapshot map.

Returns

modes
The computed POD modes.
svals
The associated singular values.
snap_count
The total number of input snapshot vectors.

pymor.algorithms.hapod.std_local_eps(tree, eps, omega, pod_on_leafs=True)[source]
image module
class pymor.algorithms.image.CollectOperatorRangeRules(source, image, extends)[source]

Bases: pymor.algorithms.rules.RuleTable

RuleTable for the estimate_image algorithm.

Attributes

CollectOperatorRangeRules action_apply_operator, action_Concatenation, action_EmpiricalInterpolatedOperator, action_recurse, rules
BasicInterface logger, logging_disabled, name, uid

class pymor.algorithms.image.CollectVectorRangeRules(image)[source]

Bases: pymor.algorithms.rules.RuleTable

RuleTable for the estimate_image algorithm.

Attributes

CollectVectorRangeRules action_as_range_array, action_Concatenation, action_recurse, action_VectorArray, rules
BasicInterface logger, logging_disabled, name, uid

pymor.algorithms.image.estimate_image(operators=(), vectors=(), domain=None, extends=False, orthonormalize=True, product=None, riesz_representatives=False)[source]

Estimate the image of given Operators for all mu.

Let operators be a list of Operators with common source and range, and let vectors be a list of VectorArrays or vector-like Operators in the range of these operators. Given a VectorArray domain of vectors in the source of the operators, this algorithms determines a VectorArray image of range vectors such that the linear span of image contains:

  • op.apply(U, mu=mu) for all operators op in operators, for all possible Parameters mu and for all VectorArrays U contained in the linear span of domain,
  • U for all VectorArrays in vectors,
  • v.as_range_array(mu) for all Operators in vectors and all possible Parameters mu.

The algorithm will try to choose image as small as possible. However, no optimality is guaranteed. The image estimation algorithm is specified by CollectOperatorRangeRules and CollectVectorRangeRules.

Parameters

operators
See above.
vectors
See above.
domain
See above. If None, an empty domain VectorArray is assumed.
extends
For some operators, e.g. EmpiricalInterpolatedOperator, as well as for all elements of vectors, image is estimated independently from the choice of domain. If extends is True, such operators are ignored. (This is useful in case these vectors have already been obtained by earlier calls to this function.)
orthonormalize
Compute an orthonormal basis for the linear span of image using the gram_schmidt algorithm.
product
Inner product Operator w.r.t. which to orthonormalize.
riesz_representatives
If True, compute Riesz representatives of the vectors in image before orthonormalizing (useful for dual norm computation when the range of the operators is a dual space).

Returns

The VectorArray image.

Raises

ImageCollectionError
Is raised when for a given Operator no image estimate is possible.

pymor.algorithms.image.estimate_image_hierarchical(operators=(), vectors=(), domain=None, extends=None, orthonormalize=True, product=None, riesz_representatives=False)[source]

Estimate the image of given Operators for all mu.

This is an extended version of estimate_image, which calls estimate_image individually for each vector of domain.

As a result, the vectors in the returned image VectorArray will be ordered by the domain vector they correspond to (starting with vectors which correspond to the elements of vectors and to Operators for which the image is estimated independently from domain).

This function also returns an image_dims list, such that the first image_dims[i+1] vectors of image correspond to the first i vectors of domain (the first image_dims[0] vectors correspond to vectors and to Operators with fixed image estimate).

Parameters

operators
See estimate_image.
vectors
See estimate_image.
domain
See estimate_image.
extends
When additional vectors have been appended to the domain VectorArray after estimate_image_hierarchical has been called, and estimate_image_hierarchical shall be called again for the extended domain array, extends can be set to (image, image_dims), where image, image_dims are the return values of the last estimate_image_hierarchical call. The old domain vectors will then be skipped during computation and image, image_dims will be modified in-place.
orthonormalize
See estimate_image.
product
See estimate_image.
riesz_representatives
See estimate_image.

Returns

image
See above.
image_dims
See above.

Raises

ImageCollectionError
Is raised when for a given Operator no image estimate is possible.
lradi module
pymor.algorithms.lradi.lyap_lrcf_solver_options(lradi_tol=1e-10, lradi_maxiter=500, lradi_shifts='projection_shifts', projection_shifts_z_columns=1, projection_shifts_init_maxiter=20, projection_shifts_init_seed=None, projection_shifts_implicit_subspace=True)[source]

Returns available Lyapunov equation solvers with default solver options.

Parameters

lradi_tol
See solve_lyap_lrcf.
lradi_maxiter
See solve_lyap_lrcf.
lradi_shifts
See solve_lyap_lrcf.
projection_shifts_z_columns
See projection_shifts.
projection_shifts_init_maxiter
See projection_shifts_init.
projection_shifts_init_seed
See projection_shifts_init.
projection_shifts_implicit_subspace
See projection_shifts.

Returns

A dict of available solvers with default solver options.

Defaults

lradi_tol, lradi_maxiter, lradi_shifts, projection_shifts_z_columns, projection_shifts_init_maxiter, projection_shifts_init_seed, projection_shifts_implicit_subspace (see pymor.core.defaults)


pymor.algorithms.lradi.projection_shifts(A, E, Z, W, prev_shifts, shift_options)[source]

Find further shift parameters for low-rank ADI iteration using Galerkin projection on spaces spanned by LR-ADI iterates.

See [PK16], pp. 92-95.

Parameters

A
The Operator A from the corresponding Lyapunov equation.
E
The Operator E from the corresponding Lyapunov equation.
Z
A VectorArray representing the currently computed low-rank solution factor.
W
A VectorArray representing the currently computed low-rank residual factor.
prev_shifts
A NumPy array containing the set of all previously used shift parameters.
shift_options
The shift options to use (see lyap_lrcf_solver_options).

Returns

shifts
A NumPy array containing a set of stable shift parameters.

pymor.algorithms.lradi.projection_shifts_init(A, E, B, shift_options)[source]

Find starting shift parameters for low-rank ADI iteration using Galerkin projection on spaces spanned by LR-ADI iterates.

See [PK16], pp. 92-95.

Parameters

A
The Operator A from the corresponding Lyapunov equation.
E
The Operator E from the corresponding Lyapunov equation.
B
The VectorArray B from the corresponding Lyapunov equation.
shift_options
The shift options to use (see lyap_lrcf_solver_options).

Returns

shifts
A NumPy array containing a set of stable shift parameters.

pymor.algorithms.lradi.solve_lyap_lrcf(A, E, B, trans=False, options=None)[source]

Compute an approximate low-rank solution of a Lyapunov equation.

See pymor.algorithms.lyapunov.solve_lyap_lrcf for a general description.

This function uses the low-rank ADI iteration as described in Algorithm 4.3 in [PK16]. We assume in projection_shifts_init for A.source.from_numpy to be implemented if projecting (A, E) with B does not give stable eigenvalues.

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
trans
Whether the first Operator in the Lyapunov equation is transposed.
options
The solver options to use (see lyap_lrcf_solver_options).

Returns

Z
Low-rank Cholesky factor of the Lyapunov equation solution, VectorArray from A.source.
lyapunov module
pymor.algorithms.lyapunov._chol(A)[source]

Cholesky decomposition.

This implementation uses SVD to compute the Cholesky factor (can be used for singular matrices).

Parameters

A
Symmetric positive semidefinite matrix as a NumPy array.

Returns

L
Cholesky factor of A (in the sense that L * L^T approximates A).

pymor.algorithms.lyapunov.mat_eqn_sparse_min_size(value=1000)[source]

Returns minimal size for which a sparse solver will be used by default.

Defaults

value (see pymor.core.defaults)


pymor.algorithms.lyapunov.solve_lyap_dense(A, E, B, trans=False, options=None, default_solver_backend='scipy')[source]

Compute the solution of a Lyapunov equation.

Returns the solution X of a (generalized) continuous-time algebraic Lyapunov equation:

  • if trans is False and E is None:

    A X + X A^T + B B^T = 0,

  • if trans is False and E is an Operator:

    A X E^T + E X A^T + B B^T = 0,

  • if trans is True and E is None:

    A^T X + X A + B^T B = 0,

  • if trans is True and E is an Operator:

    A^T X E + E^T X A + B^T B = 0.

We assume A and E are real NumPy arrays, E is invertible, and that no two eigenvalues of (A, E) sum to zero (i.e., there exists a unique solution X).

If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:

  1. pymess (see pymor.bindings.pymess.solve_lyap_dense)
  2. slycot (see pymor.bindings.slycot.solve_lyap_dense)
  3. scipy (see pymor.bindings.scipy.solve_lyap_dense)

Parameters

A
The operator A as a 2D NumPy array.
E
The operator E as a 2D NumPy array or None.
B
The operator B as a 2D NumPy array.
trans
Whether the first operator in the Lyapunov equation is transposed.
options

The solver options to use. See:

default_solver_backend
Default solver backend to use (pymess, slycot, scipy).

Returns

X
Lyapunov equation solution as a NumPy array.

Defaults

default_solver_backend (see pymor.core.defaults)


pymor.algorithms.lyapunov.solve_lyap_lrcf(A, E, B, trans=False, options=None, default_sparse_solver_backend='lradi', default_dense_solver_backend='scipy')[source]

Compute an approximate low-rank solution of a Lyapunov equation.

Returns a low-rank Cholesky factor Z such that Z Z^T approximates the solution X of a (generalized) continuous-time algebraic Lyapunov equation:

  • if trans is False and E is None:

    A X + X A^T + B B^T = 0,

  • if trans is False and E is an Operator:

    A X E^T + E X A^T + B B^T = 0,

  • if trans is True and E is None:

    A^T X + X A + B^T B = 0,

  • if trans is True and E is an Operator:

    A^T X E + E^T X A + B^T B = 0.

We assume A and E are real Operators, E is invertible, and all the eigenvalues of (A, E) all lie in the open left half-plane. Operator B needs to be given as a VectorArray from A.source, and for large-scale problems, we assume len(B) is small.

If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
trans
Whether the first Operator in the Lyapunov equation is transposed.
options

The solver options to use. See:

default_sparse_solver_backend
Default sparse solver backend to use (pymess, lradi).
default_dense_solver_backend
Default dense solver backend to use (pymess, slycot, scipy).

Returns

Z
Low-rank Cholesky factor of the Lyapunov equation solution, VectorArray from A.source.

Defaults

default_sparse_solver_backend, default_dense_solver_backend (see pymor.core.defaults)

newton module
pymor.algorithms.newton.newton(operator, rhs, initial_guess=None, mu=None, error_norm=None, least_squares=False, miniter=0, maxiter=100, rtol=-1.0, atol=-1.0, stagnation_window=3, stagnation_threshold=0.9, return_stages=False, return_residuals=False)[source]

Basic Newton algorithm.

This method solves the nonlinear equation

A(U, mu) = V

for U using the Newton method.

Parameters

operator
The Operator A. A must implement the jacobian interface method.
rhs
VectorArray of length 1 containing the vector V.
initial_guess
If not None, a VectorArray of length 1 containing an initial guess for the solution U.
mu
The Parameter for which to solve the equation.
error_norm
The norm with which the norm of the residual is computed. If None, the Euclidean norm is used.
least_squares
If True, use a least squares linear solver (e.g. for residual minimization).
miniter
Minimum amount of iterations to perform.
maxiter
Fail if the iteration count reaches this value without converging.
rtol
Finish when the residual norm has been reduced by this factor relative to the norm of the initial residual.
atol
Finish when the residual norm is below this threshold.
stagnation_window
Finish when the residual norm has not been reduced by a factor of stagnation_threshold during the last stagnation_window iterations.
stagnation_threshold
See stagnation_window.
return_stages
If True, return a VectorArray of the intermediate approximations of U after each iteration.
return_residuals
If True, return a VectorArray of all residual vectors which have been computed during the Newton iterations.

Returns

U
VectorArray of length 1 containing the computed solution
data

Dict containing the following fields:

error_sequence:NumPy array containing the residual norms after each iteration.
stages:See return_stages.
residuals:See return_residuals.

Raises

NewtonError
Raised if the Netwon algorithm failed to converge.

Defaults

miniter, maxiter, rtol, atol, stagnation_window, stagnation_threshold (see pymor.core.defaults)

pod module
pymor.algorithms.pod.pod(A, modes=None, product=None, rtol=4e-08, atol=0.0, l2_err=0.0, symmetrize=False, orthonormalize=True, check=True, check_tol=1e-10)[source]

Proper orthogonal decomposition of A.

Viewing the VectorArray A as a A.dim x len(A) matrix, the return value of this method is the VectorArray of left-singular vectors of the singular value decomposition of A, where the inner product on R^(dim(A)) is given by product and the inner product on R^(len(A)) is the Euclidean inner product.

Parameters

A
The VectorArray for which the POD is to be computed.
modes
If not None, only the first modes POD modes (singular vectors) are returned.
product
Inner product Operator w.r.t. which the POD is computed.
rtol
Singular values smaller than this value multiplied by the largest singular value are ignored.
atol
Singular values smaller than this value are ignored.
l2_err

Do not return more modes than needed to bound the l2-approximation error by this value. I.e. the number of returned modes is at most

argmin_N { sum_{n=N+1}^{infty} s_n^2 <= l2_err^2 }

where s_n denotes the n-th singular value.

symmetrize
If True, symmetrize the Gramian again before proceeding.
orthonormalize
If True, orthonormalize the computed POD modes again using the gram_schmidt algorithm.
check
If True, check the computed POD modes for orthonormality.
check_tol
Tolerance for the orthonormality check.

Returns

POD
VectorArray of POD modes.
SVALS
Sequence of singular values.

Defaults

rtol, atol, l2_err, symmetrize, orthonormalize, check, check_tol (see pymor.core.defaults)

preassemble module
class pymor.algorithms.preassemble.PreAssembleRules[source]

Bases: pymor.algorithms.rules.RuleTable

Attributes

PreAssembleRules action_AdjointOperator, action_assemble, action_identity, action_recurse, action_recurse_and_assemble, rules
BasicInterface logger, logging_disabled, name, uid

pymor.algorithms.preassemble.preassemble(obj)[source]

Preassemble non-parametric operators.

If obj is a non-parametric Operator, return obj.assemble() otherwise return obj. Recursively replaces children of obj.

projection module
class pymor.algorithms.projection.ProjectRules(range_basis, source_basis, product)[source]

Bases: pymor.algorithms.rules.RuleTable

RuleTable for the project algorithm.

Attributes

ProjectRules action_AdjointOperator, action_AffineOperator, action_apply_basis, action_Concatenation, action_ConstantOperator, action_EmpiricalInterpolatedOperator, action_generic_projection, action_LincombOperator, action_SelectionOperator, action_ZeroOperator, rules
BasicInterface logger, logging_disabled, name, uid

class pymor.algorithms.projection.ProjectToSubbasisRules(dim_range, dim_source)[source]

Bases: pymor.algorithms.rules.RuleTable

RuleTable for the project_to_subbasis algorithm.

Attributes

ProjectToSubbasisRules action_ConstantOperator, action_IdentityOperator, action_NumpyMatrixOperator, action_ProjectedEmpiciralInterpolatedOperator, action_ProjectedOperator, action_recurse, rules
BasicInterface logger, logging_disabled, name, uid

pymor.algorithms.projection.project(op, range_basis, source_basis, product=None)[source]

Petrov-Galerkin projection of a given Operator.

Given an inner product ( ⋅, ⋅), source vectors b_1, ..., b_N and range vectors c_1, ..., c_M, the projection op_proj of op is defined by

[ op_proj(e_j) ]_i = ( c_i, op(b_j) )

for all i,j, where e_j denotes the j-th canonical basis vector of R^N.

In particular, if the c_i are orthonormal w.r.t. the given product, then op_proj is the coordinate representation w.r.t. the b_i/c_i bases of the restriction of op to span(b_i) concatenated with the orthogonal projection onto span(c_i).

From another point of view, if op is viewed as a bilinear form (see apply2) and ( ⋅, ) is the Euclidean inner product, then op_proj represents the matrix of the bilinear form restricted to span(b_i) / span(c_i) (w.r.t. the b_i/c_i bases).

How the projection is realized will depend on the given Operator. While a projected NumpyMatrixOperator will again be a NumpyMatrixOperator, only a generic ProjectedOperator can be returned in general. The exact algorithm is specified in ProjectRules.

Parameters

range_basis
The vectors c_1, ..., c_M as a VectorArray. If None, no projection in the range space is performed.
source_basis
The vectors b_1, ..., b_N as a VectorArray or None. If None, no restriction of the source space is performed.
product
An Operator representing the inner product. If None, the Euclidean inner product is chosen.

Returns

The projected Operator op_proj.


pymor.algorithms.projection.project_to_subbasis(op, dim_range=None, dim_source=None)[source]

Project already projected Operator to a subbasis.

The purpose of this method is to further project an operator that has been obtained through project to subbases of the original projection bases, i.e.

project_to_subbasis(project(op, r_basis, s_basis, prod), dim_range, dim_source)

should be the same as

project(op, r_basis[:dim_range], s_basis[:dim_source], prod)

For a NumpyMatrixOperator this amounts to extracting the upper-left (dim_range, dim_source) corner of its matrix.

The subbasis projection algorithm is specified in ProjectToSubbasisRules.

Parameters

dim_range
Dimension of the range subbasis.
dim_source
Dimension of the source subbasis.

Returns

The projected Operator.

riccati module
pymor.algorithms.riccati.solve_pos_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None, default_dense_solver_backend='scipy')[source]

Compute an approximate low-rank solution of a positive Riccati equation.

Returns a low-rank Cholesky factor Z such that Z Z^T approximates the solution X of a (generalized) positive continuous-time algebraic Riccati equation:

  • if trans is False

    A X E^T + E X A^T
+ (E X C^T + S) R^{-1} (E X C^T + S)^T
+ B B^T = 0.

  • if trans is True

    A^T X E + E^T X A
+ (E^T X B + S) R^{-1} (E^T X B + S)^T
+ C^T C = 0.

If E is None, it is taken to be identity, and similarly for R. If S is None, it is taken to be zero.

If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:

  1. pymess (see pymor.bindings.pymess.solve_pos_ricc_lrcf),
  2. slycot (see pymor.bindings.slycot.solve_pos_ricc_lrcf),
  3. scipy (see pymor.bindings.scipy.solve_pos_ricc_lrcf).

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
C
The operator C as a VectorArray from A.source.
R
The operator R as a 2D NumPy array or None.
S
The operator S as a VectorArray from A.source or None.
trans
Whether the first Operator in the positive Riccati equation is transposed.
options

The solver options to use. See:

default_dense_solver_backend
Default dense solver backend to use (pymess, slycot, scipy).

Returns

Z
Low-rank Cholesky factor of the positive Riccati equation solution, VectorArray from A.source.

Defaults

default_dense_solver_backend (see pymor.core.defaults)


pymor.algorithms.riccati.solve_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None, default_sparse_solver_backend='pymess', default_dense_solver_backend='scipy')[source]

Compute an approximate low-rank solution of a Riccati equation.

Returns a low-rank Cholesky factor Z such that Z Z^T approximates the solution X of a (generalized) continuous-time algebraic Riccati equation:

  • if trans is False

    A X E^T + E X A^T
- (E X C^T + S) R^{-1} (E X C^T + S)^T
+ B B^T = 0.

  • if trans is True

    A^T X E + E^T X A
- (E^T X B + S) R^{-1} (E^T X B + S)^T
+ C^T C = 0.

If E is None, it is taken to be identity, and similarly for R. If S is None, it is taken to be zero.

We assume:

  • A and E are real Operators,
  • B, C and S are real VectorArrays from A.source,
  • R is a real NumPy array,
  • (E, A, B, C) is stabilizable and detectable,
  • R is symmetric positive definite, and
  • B B^T - S R^{-1} S^T (C^T C - S R^{-1} S^T) is positive semi-definite trans is False (True).

For large-scale problems, we additionally assume that len(B) and len(C) are small.

If the solver is not specified using the options argument, a solver backend is chosen based on availability in the following order:

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
C
The operator C as a VectorArray from A.source.
R
The operator R as a 2D NumPy array or None.
S
The operator S as a VectorArray from A.source or None.
trans
Whether the first Operator in the Riccati equation is transposed.
options

The solver options to use. See:

default_sparse_solver_backend
Default sparse solver backend to use (pymess).
default_dense_solver_backend
Default dense solver backend to use (pymess, slycot, scipy).

Returns

Z
Low-rank Cholesky factor of the Riccati equation solution, VectorArray from A.source.

Defaults

default_sparse_solver_backend, default_dense_solver_backend (see pymor.core.defaults)

rules module
class pymor.algorithms.rules.RuleTable(use_caching=False)[source]

Bases: pymor.core.interfaces.BasicInterface

Define algorithm by a table of match conditions and corresponding actions.

RuleTable manages a table of rules, stored in the rules attributes, which can be applied to given objects.

A new table is created by subclassing RuleTable and defining new methods which are decorated with match_class, match_generic or another rule subclass. The order of the method definitions determines the order in which the defined rules are applied.

Parameters

use_caching
If True, cache results of apply.
rules

list of all defined rules.

apply(obj)[source]

Sequentially apply rules to given object.

This method iterates over all rules of the given RuleTable. For each rule, it is checked if it matches the given object. If False, the next rule in the table is considered. If True the corresponding action is executed with obj as parameter. If execution of action raises RuleNotMatchingError, the rule is considered as not matching, and execution continues with evaluation of the next rule. Otherwise, execution is stopped and the return value of rule.action is returned to the caller.

If no rule matches, a NoMatchingRuleError is raised.

Parameters

obj
The object to apply the RuleTable to.

Returns

Return value of the action of the first matching rule in the table.

Raises

NoMatchingRuleError
No rule could be applied to the given object.
apply_children(obj, children=None)[source]

Apply rules to all children of the given object.

This method calls apply to each child of the given object. The children of the object are either provided by the children parameter or automatically inferred by the get_children method.

Parameters

obj
The object to apply the RuleTable to.
children
None or a list of attribute names defining the children to consider.

Returns

Result of : meth:apply for all given children.

classmethod get_children(obj)[source]

Determine children of given object.

This method returns a list of the names of all attributes a, for which one of the folling is true:

  1. a is an Operator.
  2. a is a mapping and each of its values is either an Operator or None.
  3. a is an iterable and each of its elements is either an Operator or None.
replace_children(obj, children=None)[source]

Replace children of object according to rule table.

Same as apply_children, but additionally calls obj.with_ to replace the children of obj with the result of the corresponding apply call.


class pymor.algorithms.rules.RuleTableMeta(name, bases, namespace)[source]

Bases: pymor.core.interfaces.UberMeta

Meta class for RuleTable.

Methods

ABCMeta register, __instancecheck__, __subclasscheck__
type mro, __dir__, __prepare__, __sizeof__, __subclasses__
static __new__(cls, name, parents, dct)[source]

I copy docstrings from base class methods to deriving classes.

Copying of docstrings is disabled when the PYMOR_WITH_SPHINX environment variable is set to 1.

__repr__()[source]

Return repr(self).

__str__()

Return repr(self).


class pymor.algorithms.rules.match_class(*classes)[source]

Bases: pymor.algorithms.rules.rule

rule that matches when obj is instance of one of the given classes.

Attributes

match_class condition_type
rule action, action_description, condition_description, source
matches(obj)[source]

Returns True if given object matches the condition.


class pymor.algorithms.rules.match_generic(condition, condition_description=None)[source]

Bases: pymor.algorithms.rules.rule

rule with matching condition given by an arbitrary function.

Parameters

condition
Function of one argument which checks if given object matches condition.
condition_description
Optional string describing the condition implemented by condition.

Attributes

match_generic condition_type
rule action, action_description, condition_description, source
matches(obj)[source]

Returns True if given object matches the condition.


pymor.algorithms.rules.print_children(obj)[source]

class pymor.algorithms.rules.rule[source]

Bases: object

Decorator to make a method a rule in a given RuleTable.

The decorated function will become the action to perform in case the rule matches. Matching conditions are specified by subclassing and overriding the matches method.

Methods

rule matches

Attributes

rule action, action_description, condition_description, condition_type, source
action

Method to call in case the rule matches.

__call__(action)[source]

Call self as a function.

__repr__()[source]

Return repr(self).

matches(obj)[source]

Returns True if given object matches the condition.

sylvester module
pymor.algorithms.sylvester.solve_sylv_schur(A, Ar, E=None, Er=None, B=None, Br=None, C=None, Cr=None)[source]

Solve Sylvester equation by Schur decomposition.

Solves Sylvester equation

A V E_r^T + E V A_r^T + B B_r^T = 0

or

A^T W E_r + E^T W A_r + C^T C_r = 0

or both using (generalized) Schur decomposition (Algorithms 3 and 4 in [BKS11]), if the necessary parameters are given.

Parameters

A
Real Operator.
Ar
Real Operator. It is converted into a NumPy array using to_matrix.
E
Real Operator or None (then assumed to be the identity).
Er
Real Operator or None (then assumed to be the identity). It is converted into a NumPy array using to_matrix.
B
Real Operator or None.
Br
Real Operator or None. It is converted into a VectorArray using Br.as_source_array().
C
Real Operator or None.
Cr
Real Operator or None. It is converted into a VectorArray using Cr.as_range_array().

Returns

V
Returned if B and Br are given, VectorArray from A.source.
W
Returned if C and Cr are given, VectorArray from A.source.

Raises

ValueError
If V and W cannot be returned.
timestepping module

This module provides generic time-stepping algorithms for the solution of instationary problems.

The algorithms are generic in the sense that each algorithms operates exclusively on Operators and VectorArrays. In particular, the algorithms can also be used to turn an arbitrary stationary Discretization provided by an external library into an instationary Discretization.

Currently, implementations of explicit_euler and implicit_euler time-stepping are provided. The TimeStepperInterface defines a common interface that has to be fulfilled by the time-steppers used by InstationaryDiscretization. The classes ExplicitEulerTimeStepper and ImplicitEulerTimeStepper encapsulate explicit_euler and implicit_euler to provide this interface.


class pymor.algorithms.timestepping.ExplicitEulerTimeStepper(nt)[source]

Bases: pymor.algorithms.timestepping.TimeStepperInterface

Explicit Euler time-stepper.

Solves equations of the form

M * d_t u + A(u, mu, t) = F(mu, t).

Parameters

nt
The number of time-steps the time-stepper will perform.
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]

Apply time-stepper to the equation

M * d_t u + A(u, mu, t) = F(mu, t).

Parameters

initial_time
The time at which to begin time-stepping.
end_time
The time until which to perform time-stepping.
initial_data
The solution vector at initial_time.
operator
The Operator A.
rhs
The right-hand side F (either VectorArray of length 1 or Operator with source.dim == 1). If None, zero right-hand side is assumed.
mass
The Operator M. If None, the identity operator is assumed.
mu
Parameter for which operator and rhs are evaluated. The current time is added to mu with key _t.
num_values
The number of returned vectors of the solution trajectory. If None, each intermediate vector that is calculated is returned.

Returns

VectorArray containing the solution trajectory.


class pymor.algorithms.timestepping.ImplicitEulerTimeStepper(nt, solver_options='operator')[source]

Bases: pymor.algorithms.timestepping.TimeStepperInterface

Implict Euler time-stepper.

Solves equations of the form

M * d_t u + A(u, mu, t) = F(mu, t).

Parameters

nt
The number of time-steps the time-stepper will perform.
solver_options
The solver_options used to invert M + dt*A. The special values 'mass' and 'operator' are recognized, in which case the solver_options of M (resp. A) are used.
solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]

Apply time-stepper to the equation

M * d_t u + A(u, mu, t) = F(mu, t).

Parameters

initial_time
The time at which to begin time-stepping.
end_time
The time until which to perform time-stepping.
initial_data
The solution vector at initial_time.
operator
The Operator A.
rhs
The right-hand side F (either VectorArray of length 1 or Operator with source.dim == 1). If None, zero right-hand side is assumed.
mass
The Operator M. If None, the identity operator is assumed.
mu
Parameter for which operator and rhs are evaluated. The current time is added to mu with key _t.
num_values
The number of returned vectors of the solution trajectory. If None, each intermediate vector that is calculated is returned.

Returns

VectorArray containing the solution trajectory.


class pymor.algorithms.timestepping.TimeStepperInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface

Interface for time-stepping algorithms.

Algorithms implementing this interface solve time-dependent problems of the form

M * d_t u + A(u, mu, t) = F(mu, t).

Time-steppers used by InstationaryDiscretization have to fulfill this interface.

solve(initial_time, end_time, initial_data, operator, rhs=None, mass=None, mu=None, num_values=None)[source]

Apply time-stepper to the equation

M * d_t u + A(u, mu, t) = F(mu, t).

Parameters

initial_time
The time at which to begin time-stepping.
end_time
The time until which to perform time-stepping.
initial_data
The solution vector at initial_time.
operator
The Operator A.
rhs
The right-hand side F (either VectorArray of length 1 or Operator with source.dim == 1). If None, zero right-hand side is assumed.
mass
The Operator M. If None, the identity operator is assumed.
mu
Parameter for which operator and rhs are evaluated. The current time is added to mu with key _t.
num_values
The number of returned vectors of the solution trajectory. If None, each intermediate vector that is calculated is returned.

Returns

VectorArray containing the solution trajectory.


pymor.algorithms.timestepping.explicit_euler(A, F, U0, t0, t1, nt, mu=None, num_values=None)[source]

pymor.algorithms.timestepping.implicit_euler(A, F, M, U0, t0, t1, nt, mu=None, num_values=None, solver_options='operator')[source]
to_matrix module
class pymor.algorithms.to_matrix.ToMatrixRules(format, mu)[source]

Bases: pymor.algorithms.rules.RuleTable

Attributes

ToMatrixRules action_AdjointOperator, action_BlockOperator, action_ComponentProjection, action_Concatenation, action_IdentityOperator, action_LincombOperator, action_NumpyMatrixOperator, action_VectorArrayOperator, action_ZeroOperator, rules
BasicInterface logger, logging_disabled, name, uid

pymor.algorithms.to_matrix.to_matrix(op, format=None, mu=None)[source]

Convert a linear Operator to a matrix.

Parameters

op
The Operator to convert.
format
Format of the resulting matrix: NumPy array if ‘dense’, otherwise the appropriate SciPy spmatrix. If None, a choice between dense and sparse format is automatically made.
mu
The Parameter for which to convert op.

Returns

res
The matrix equivalent to op.
pymor.analyticalproblems package
Submodules
burgers module
pymor.analyticalproblems.burgers.burgers_problem(v=1.0, circle=True, initial_data_type='sin', parameter_range=(1.0, 2.0))[source]

One-dimensional Burgers-type problem.

The problem is to solve

∂_t u(x, t, μ)  +  ∂_x (v * u(x, t, μ)^μ) = 0
                               u(x, 0, μ) = u_0(x)

for u with t in [0, 0.3] and x in [0, 2].

Parameters

v
The velocity v.
circle
If True, impose periodic boundary conditions. Otherwise Dirichlet left, outflow right.
initial_data_type
Type of initial data ('sin' or 'bump').
parameter_range
The interval in which μ is allowed to vary.

pymor.analyticalproblems.burgers.burgers_problem_2d(vx=1.0, vy=1.0, torus=True, initial_data_type='sin', parameter_range=(1.0, 2.0))[source]

Two-dimensional Burgers-type problem.

The problem is to solve

∂_t u(x, t, μ)  +  ∇ ⋅ (v * u(x, t, μ)^μ) = 0
                               u(x, 0, μ) = u_0(x)

for u with t in [0, 0.3], x in [0, 2] x [0, 1].

Parameters

vx
The x component of the velocity vector v.
vy
The y component of the velocity vector v.
torus
If True, impose periodic boundary conditions. Otherwise, Dirichlet left and bottom, outflow top and right.
initial_data_type
Type of initial data ('sin' or 'bump').
parameter_range
The interval in which μ is allowed to vary.
elliptic module
class pymor.analyticalproblems.elliptic.StationaryProblem(domain, rhs=None, diffusion=None, advection=None, nonlinear_advection=None, nonlinear_advection_derivative=None, reaction=None, nonlinear_reaction=None, nonlinear_reaction_derivative=None, dirichlet_data=None, neumann_data=None, robin_data=None, functionals=None, parameter_space=None, name=None)[source]

Bases: pymor.core.interfaces.ImmutableInterface

Linear elliptic problem description.

The problem consists in solving

- ∇ ⋅ [d(x, μ) ∇ u(x, μ)] + ∇ ⋅ [f(x, u(x, μ), μ)] + c(x, u(x, μ), μ) = f(x, μ)

for u.

Parameters

domain
A DomainDescription of the domain the problem is posed on.
rhs
The Function f(x, μ). rhs.dim_domain has to agree with the dimension of domain, whereas rhs.shape_range has to be ().
diffusion
The Function d(x, μ) with shape_range of either () or (dim domain, dim domain).
advection
The Function f, only depending on x, with shape_range of (dim domain,).
nonlinear_advection
The Function f, only depending on u, with shape_range of (dim domain,).
nonlinear_advection_derivative
The derivative of f, only depending on u, with respect to u.
reaction
The Function c, only depending on x, with shape_range of ().
nonlinear_reaction
The Function c, only depending on u, with shape_range of ().
nonlinear_reaction_derivative
The derivative of the Function c, only depending on u, with shape_range of ().
dirichlet_data
Function providing the Dirichlet boundary values.
neumann_data
Function providing the Neumann boundary values.
robin_data
Tuple of two Functions providing the Robin parameter and boundary values.
functionals

Dict of additional functionals to assemble. Each value must be a tuple of the form (functional_type, data) where functional_type is a string defining the type of functional to assemble and data is a Function holding the corresponding coefficient function. Currently implemented functional_types are:

l2:Evaluate the l2-product with the given data function.
l2_boundary:Evaluate the l2-product with the given data function on the boundary.
parameter_space
ParameterSpace for the problem.
name
Name of the problem.
domain
rhs
diffusion
advection
nonlinear_advection
nonlinear_advection_derivative
reaction
nonlinear_reaction
nonlinear_reaction_derivative
dirichlet_data
neumann_data
robin_data
functionals
helmholtz module
pymor.analyticalproblems.helmholtz.helmholtz_problem(domain=RectDomain([[0 0], [1 1]]), rhs=None, parameter_range=(0.0, 100.0), dirichlet_data=None, neumann_data=None)[source]

Helmholtz equation problem.

This problem is to solve the Helmholtz equation

- ∆ u(x, k) - k^2 u(x, k) = f(x, k)

on a given domain.

Parameters

domain
A DomainDescription of the domain the problem is posed on.
rhs
The Function f(x, μ).
parameter_range
A tuple (k_min, k_max) describing the interval in which k is allowd to vary.
dirichlet_data
Function providing the Dirichlet boundary values.
neumann_data
Function providing the Neumann boundary values.
instationary module
class pymor.analyticalproblems.instationary.InstationaryProblem(stationary_part, initial_data, T=1.0, parameter_space=None, name=None)[source]

Bases: pymor.core.interfaces.ImmutableInterface

Instationary problem description.

This class describes an instationary problem of the form

|    ∂_t u(x, t, μ) + A(u(x, t, μ), t, μ) = f(x, t, μ),
|                              u(x, 0, μ) = u_0(x, μ)

where A, f are given by the problem’s stationary_part and t is allowed to vary in the interval [0, T].

Parameters

stationary_part
The stationary part of the problem.
initial_data
Function providing the initial values u_0.
T
The final time T.
parameter_space
ParameterSpace for the problem.
name
Name of the problem.
T
stationary_part
parameter_space
name
with_(**kwargs)[source]

Returns a copy with changed attributes.

The default implementation is to create a new class instance with the given keyword arguments as arguments for __init__. Missing arguments are obtained form instance attributes with the same name.

Parameters

**kwargs
Names of attributes to change with their new values. Each attribute name has to be contained in with_arguments.

Returns

Copy of self with changed attributes.

text module
pymor.analyticalproblems.text.text_problem(text='pyMOR', font_name=None)[source]
thermalblock module
pymor.analyticalproblems.thermalblock.thermal_block_problem(num_blocks=(3, 3), parameter_range=(0.1, 1))[source]

Analytical description of a 2D ‘thermal block’ diffusion problem.

The problem is to solve the elliptic equation

- ∇ ⋅ [ d(x, μ) ∇ u(x, μ) ] = f(x, μ)

on the domain [0,1]^2 with Dirichlet zero boundary values. The domain is partitioned into nx x ny blocks and the diffusion function d(x, μ) is constant on each such block (i,j) with value μ_ij.

----------------------------
|        |        |        |
|  μ_11  |  μ_12  |  μ_13  |
|        |        |        |
|---------------------------
|        |        |        |
|  μ_21  |  μ_22  |  μ_23  |
|        |        |        |
----------------------------

Parameters

num_blocks
The tuple (nx, ny)
parameter_range
A tuple (μ_min, μ_max). Each Parameter component μ_ij is allowed to lie in the interval [μ_min, μ_max].
pymor.bindings package
Submodules
fenics module
ngsolve module
pyamg module
pymess module
scipy module
pymor.bindings.scipy.apply_inverse(op, V, options=None, least_squares=False, check_finite=True, default_solver='scipy_spsolve', default_least_squares_solver='scipy_least_squares_lsmr')[source]

Solve linear equation system.

Applies the inverse of op to the vectors in rhs using SciPy.

Parameters

op
The linear, non-parametric Operator to invert.
rhs
VectorArray of right-hand sides for the equation system.
options
The solver_options to use (see solver_options).
least_squares
If True, return least squares solution.
check_finite
Test if solution only contains finite values.
default_solver
Default solver to use (scipy_spsolve, scipy_bicgstab, scipy_bicgstab_spilu, scipy_lgmres, scipy_least_squares_lsmr, scipy_least_squares_lsqr).
default_least_squares_solver
Default solver to use for least squares problems (scipy_least_squares_lsmr, scipy_least_squares_lsqr).

Returns

VectorArray of the solution vectors.

Defaults

check_finite, default_solver, default_least_squares_solver (see pymor.core.defaults)


pymor.bindings.scipy.lyap_dense_solver_options()[source]

Return available dense Lyapunov equation solvers with default solver options for the SciPy backend.

Returns

A dict of available solvers with default solver options.


pymor.bindings.scipy.lyap_lrcf_solver_options()[source]

Returns available Lyapunov equation solvers with default solver options for the SciPy backend.

Returns

A dict of available solvers with default solver options.


pymor.bindings.scipy.matrix_astype_nocopy(matrix, dtype)[source]

pymor.bindings.scipy.pos_ricc_lrcf_solver_options()[source]

Returns available positive Riccati equation solvers with default solver options for the SciPy backend.

Returns

A dict of available solvers with default solver options.


pymor.bindings.scipy.ricc_lrcf_solver_options()[source]

Returns available Riccati equation solvers with default solver options for the SciPy backend.

Returns

A dict of available solvers with default solver options.


pymor.bindings.scipy.solve_lyap_dense(A, E, B, trans=False, options=None)[source]

Compute the solution of a Lyapunov equation.

See pymor.algorithms.lyapunov.solve_lyap_dense for a general description.

This function uses scipy.linalg.solve_continuous_lyapunov, which is a dense solver for Lyapunov equations with E=I.

Note

If E is not None, the problem will be reduced to a standard continuous-time algebraic Lyapunov equation by inverting E.

Parameters

A
The operator A as a 2D NumPy array.
E
The operator E as a 2D NumPy array or None.
B
The operator B as a 2D NumPy array.
trans
Whether the first operator in the Lyapunov equation is transposed.
options
The solver options to use (see lyap_dense_solver_options).

Returns

X
Lyapunov equation solution as a NumPy array.

pymor.bindings.scipy.solve_lyap_lrcf(A, E, B, trans=False, options=None)[source]

Compute an approximate low-rank solution of a Lyapunov equation.

See pymor.algorithms.lyapunov.solve_lyap_lrcf for a general description.

This function uses scipy.linalg.solve_continuous_lyapunov, which is a dense solver for Lyapunov equations with E=I. Therefore, we assume A and E can be converted to NumPy arrays using to_matrix and that B.to_numpy is implemented.

Note

If E is not None, the problem will be reduced to a standard continuous-time algebraic Lyapunov equation by inverting E.

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
trans
Whether the first Operator in the Lyapunov equation is transposed.
options
The solver options to use (see lyap_lrcf_solver_options).

Returns

Z
Low-rank Cholesky factor of the Lyapunov equation solution, VectorArray from A.source.

pymor.bindings.scipy.solve_pos_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None)[source]

Compute an approximate low-rank solution of a positive Riccati equation.

See pymor.algorithms.riccati.solve_pos_ricc_lrcf for a general description.

This function uses scipy.linalg.solve_continuous_are, which is a dense solver. Therefore, we assume all Operators and VectorArrays can be converted to NumPy arrays using to_matrix and to_numpy.

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
C
The operator C as a VectorArray from A.source.
R
The operator R as a 2D NumPy array or None.
S
The operator S as a VectorArray from A.source or None.
trans
Whether the first Operator in the positive Riccati equation is transposed.
options
The solver options to use (see pos_ricc_lrcf_solver_options).

Returns

Z
Low-rank Cholesky factor of the positive Riccati equation solution, VectorArray from A.source.

pymor.bindings.scipy.solve_ricc_lrcf(A, E, B, C, R=None, S=None, trans=False, options=None)[source]

Compute an approximate low-rank solution of a Riccati equation.

See pymor.algorithms.riccati.solve_ricc_lrcf for a general description.

This function uses scipy.linalg.solve_continuous_are, which is a dense solver. Therefore, we assume all Operators and VectorArrays can be converted to NumPy arrays using to_matrix and to_numpy.

Parameters

A
The Operator A.
E
The Operator E or None.
B
The operator B as a VectorArray from A.source.
C
The operator C as a VectorArray from A.source.
R
The operator R as a 2D NumPy array or None.
S
The operator S as a VectorArray from A.source or None.
trans
Whether the first Operator in the Riccati equation is transposed.
options
The solver options to use (see ricc_lrcf_solver_options).

Returns

Z
Low-rank Cholesky factor of the Riccati equation solution, VectorArray from A.source.

pymor.bindings.scipy.solver_options(bicgstab_tol=1e-15, bicgstab_maxiter=None, spilu_drop_tol=0.0001, spilu_fill_factor=10, spilu_drop_rule=None, spilu_permc_spec='COLAMD', spsolve_permc_spec='COLAMD', spsolve_keep_factorization=True, lgmres_tol=1e-05, lgmres_maxiter=1000, lgmres_inner_m=39, lgmres_outer_k=3, least_squares_lsmr_damp=0.0, least_squares_lsmr_atol=1e-06, least_squares_lsmr_btol=1e-06, least_squares_lsmr_conlim=100000000.0, least_squares_lsmr_maxiter=None, least_squares_lsmr_show=False, least_squares_lsqr_damp=0.0, least_squares_lsqr_atol=1e-06, least_squares_lsqr_btol=1e-06, least_squares_lsqr_conlim=100000000.0, least_squares_lsqr_iter_lim=None, least_squares_lsqr_show=False)[source]

Returns available solvers with default solver_options for the SciPy backend.

Parameters

bicgstab_tol
See scipy.sparse.linalg.bicgstab.
bicgstab_maxiter
See scipy.sparse.linalg.bicgstab.
spilu_drop_tol
See scipy.sparse.linalg.spilu.
spilu_fill_factor
See scipy.sparse.linalg.spilu.
spilu_drop_rule
See scipy.sparse.linalg.spilu.
spilu_permc_spec
See scipy.sparse.linalg.spilu.
spsolve_permc_spec
See scipy.sparse.linalg.spsolve.
spsolve_keep_factorization
See scipy.sparse.linalg.spsolve.
lgmres_tol
See scipy.sparse.linalg.lgmres.
lgmres_maxiter
See scipy.sparse.linalg.lgmres.
lgmres_inner_m
See scipy.sparse.linalg.lgmres.
lgmres_outer_k
See scipy.sparse.linalg.lgmres.
least_squares_lsmr_damp
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_atol
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_btol
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_conlim
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_maxiter
See scipy.sparse.linalg.lsmr.
least_squares_lsmr_show
See scipy.sparse.linalg.lsmr.
least_squares_lsqr_damp
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_atol
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_btol
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_conlim
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_iter_lim
See scipy.sparse.linalg.lsqr.
least_squares_lsqr_show
See scipy.sparse.linalg.lsqr.

Returns

A dict of available solvers with default solver_options.

Defaults

bicgstab_tol, bicgstab_maxiter, spilu_drop_tol, spilu_fill_factor, spilu_drop_rule, spilu_permc_spec, spsolve_permc_spec, spsolve_keep_factorization, lgmres_tol, lgmres_maxiter, lgmres_inner_m, lgmres_outer_k, least_squares_lsmr_damp, least_squares_lsmr_atol, least_squares_lsmr_btol, least_squares_lsmr_conlim, least_squares_lsmr_maxiter, least_squares_lsmr_show, least_squares_lsqr_atol, least_squares_lsqr_btol, least_squares_lsqr_conlim, least_squares_lsqr_iter_lim, least_squares_lsqr_show (see pymor.core.defaults)

slycot module
pymor.core package
Submodules
cache module

This module provides the caching facilities of pyMOR.

Any class that wishes to provide cached method calls should derive from CacheableInterface. Methods which are to be cached can then be marked using the cached decorator.

To ensure consistency, CacheableInterface derives from ImmutableInterface: The return value of a cached method call should only depend on its arguments as well as the immutable state of the class instance.

Making this assumption, the keys for cache lookup are created from the following data:

  1. the instance’s state id in case of a persistent CacheRegion, else the instance’s uid,
  2. the method’s __name__,
  3. the state id of the arguments,
  4. the state id of pyMOR’s global defaults.

Note that instances of ImmutableInterface are allowed to have mutable private attributes. It is the implementors responsibility not to break things. (See this warning.)

Backends for storage of cached return values derive from CacheRegion. Currently two backends are provided for memory-based and disk-based caching (MemoryRegion and SQLiteRegion). The available regions are stored in the module level cache_regions dict. The user can add additional regions (e.g. multiple disk cache regions) as required. CacheableInterface.cache_region specifies a key of the cache_regions dict to select a cache region which should be used by the instance. (Setting cache_region to None or 'none' disables caching.)

By default, a ‘memory’, a ‘disk’ and a ‘persistent’ cache region are configured. The paths and maximum sizes of the disk regions, as well as the maximum number of keys of the memory cache region can be configured via the pymor.core.cache.default_regions.disk_path, pymor.core.cache.default_regions.disk_max_size, pymor.core.cache.default_regions.persistent_path, pymor.core.cache.default_regions.persistent_max_size and pymor.core.cache.default_regions.memory_max_keys defaults.

There two ways to disable and enable caching in pyMOR:

  1. Calling disable_caching (enable_caching), to disable (enable) caching globally.
  2. Calling CacheableInterface.disable_caching (CacheableInterface.enable_caching) to disable (enable) caching for a given instance.

Caching of a method is only active if caching has been enabled both globally (enabled by default) and on instance level. For debugging purposes, it is moreover possible to set the environment variable PYMOR_CACHE_DISABLE=1 which overrides any call to enable_caching.

A cache region can be emptied using CacheRegion.clear. The function clear_caches clears each cache region registered in cache_regions.


class pymor.core.cache.CacheRegion[source]

Bases: object

Base class for all pyMOR cache regions.

Methods

CacheRegion clear, get, set

Attributes

CacheRegion persistent
persistent

If True, cache entries are kept between multiple program runs.

clear()[source]

Clear the entire cache region.

get(key)[source]

Return cache entry for given key.

Parameters

key
The key for the cache entry.

Returns

(True, entry)
in case the key has been found in the cache region.
(False, None)
in case the key is not present in the cache region.
set(key, value)[source]

Set cache entry for key to given value.

This method is usually called only once for any given key (with the exemption of issues due to concurrency).


class pymor.core.cache.CacheableInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface

Base class for anything that wants to use our built-in caching.

cache_region

Name of the CacheRegion to use. Must correspond to a key in the cache_regions dict. If None or 'none', caching is disabled.

cached_method_call(method, *args, **kwargs)[source]

Call a given method and cache the return value.

This method can be used as an alternative to the cached decorator.

Parameters

method
The method that is to be called. This has to be a method of self.
args
Positional arguments for method.
kwargs
Keyword arguments for method

Returns

The (possibly cached) return value of method(*args, **kwargs).

disable_caching()[source]

Disable caching for this instance.

enable_caching(region)[source]

Enable caching for this instance.

When setting the object’s cache region to a persistent CacheRegion, the object’s state id will be computed.

Parameters

region
Name of the CacheRegion to use. Must correspond to a key in the cache_regions dict. If None or 'none', caching is disabled.

class pymor.core.cache.MemoryRegion(max_keys)[source]

Bases: pymor.core.cache.CacheRegion

Attributes

MemoryRegion NO_VALUE
CacheRegion persistent
clear()[source]

Clear the entire cache region.

get(key)[source]

Return cache entry for given key.

Parameters

key
The key for the cache entry.

Returns

(True, entry)
in case the key has been found in the cache region.
(False, None)
in case the key is not present in the cache region.
set(key, value)[source]

Set cache entry for key to given value.

This method is usually called only once for any given key (with the exemption of issues due to concurrency).


class pymor.core.cache.SQLiteRegion(path, max_size, persistent)[source]

Bases: pymor.core.cache.CacheRegion

Methods

SQLiteRegion clear, get, housekeeping, set

Attributes

CacheRegion persistent
clear()[source]

Clear the entire cache region.

get(key)[source]

Return cache entry for given key.

Parameters

key
The key for the cache entry.

Returns

(True, entry)
in case the key has been found in the cache region.
(False, None)
in case the key is not present in the cache region.
set(key, value)[source]

Set cache entry for key to given value.

This method is usually called only once for any given key (with the exemption of issues due to concurrency).


pymor.core.cache.cached(function)[source]

Decorator to make a method of CacheableInterface actually cached.


pymor.core.cache.cleanup_non_persisten_regions()[source]

pymor.core.cache.clear_caches()[source]

Clear all cache regions.


pymor.core.cache.default_regions(disk_path='/tmp/pymor.cache.docs', disk_max_size=1073741824, persistent_path='/tmp/pymor.persistent.cache.docs', persistent_max_size=1073741824, memory_max_keys=1000)[source]

pymor.core.cache.disable_caching()[source]

Globally disable caching.


pymor.core.cache.enable_caching()[source]

Globally enable caching.

config module
class pymor.core.config.Config[source]

Bases: object

Attributes

Config version
__dir__(old=False)[source]

Default dir() implementation.

__repr__()[source]

Return repr(self).


pymor.core.config.is_windows_platform()[source]
defaults module

This module contains pyMOR’s facilities for handling default values.

A default value in pyMOR is always the default value of some function argument. To mark the value of an optional function argument as a user-modifiable default value use the defaults decorator. As an additional feature, if None is passed for such an argument, its default value is used instead of None. This is useful for writing code of the following form:

@default('option')
def algorithm(U, option=42):
    ...

def method_called_by_user(V, option_for_algorithm=None):
    ...
    algorithm(U, option=option_for_algorithm)
    ...

If the user does not provide option_for_algorithm to method_called_by_user, the default 42 is automatically chosen without the implementor of method_called_by_user having to care about this.

The user interface for handling default values in pyMOR is provided by set_defaults, load_defaults_from_file, write_defaults_to_file and print_defaults.

If pyMOR is imported, it will automatically search for a configuration file named pymor_defaults.py in the current working directory. If found, the file is loaded via load_defaults_from_file. However, as a security precaution, the file will only be loaded if it is owned by the user running the Python interpreter (load_defaults_from_file uses exec to load the configuration). As an alternative, the environment variable PYMOR_DEFAULTS can be used to specify the path of a configuration file. If empty or set to NONE, no configuration file will be loaded whatsoever.

Warning

The state of pyMOR’s global defaults enters the calculation of each state id. Thus, if you first instantiate an immutable object and then change the defaults, the resulting object will have a different state id than if you first change the defaults. (This is necessary as the object can save internal state upon initialization, which depends on the state of the global defaults.) As a consequence, the key generated for caching will depend on the time the defaults have been changed. While no wrong results will be produced, changing defaults at different times will cause unnecessary cache misses and will pollute the cache with duplicate entries.

An exemption from this rule are defaults which are listed in the sid_ignore argument of the defaults decorator. Such defaults will not enter the state id calculation. This allows the user to change defaults related to input/output, e.g. logging, without breaking caching. Before marking defaults as ignored in your own code, however, make sure to double check that these defaults will not affect the result of any mathematical algorithm.


class pymor.core.defaults.DefaultContainer[source]

Bases: object

Internal singleton class holding all default values defined in pyMOR.

Not to be used directly.

Methods

DefaultContainer get, import_all, keys, update

Attributes

DefaultContainer sid
static __new__(cls)[source]

Create and return a new object. See help(type) for accurate signature.


pymor.core.defaults.defaults(*args, sid_ignore=())[source]

Function decorator for marking function arguments as user-configurable defaults.

If a function decorated with defaults is called, the values of the marked default parameters are set to the values defined via load_defaults_from_file or set_defaults in case no value has been provided by the caller of the function. Moreover, if None is passed as a value for a default argument, the argument is set to its default value, as well. If no value has been specified using set_defaults or load_defaults_from_file, the default value provided in the function signature is used.

If the argument arg of function f in sub-module m of package p is marked as a default value, its value will be changeable by the aforementioned methods under the path p.m.f.arg.

Note that the defaults decorator can also be used in user code.

Parameters

args
List of strings containing the names of the arguments of the decorated function to mark as pyMOR defaults. Each of these arguments has to be a keyword argument (with a default value).
sid_ignore
List of strings naming the defaults in args which should not enter state id calculation (because they do not affect the outcome of any computation). Such defaults will typically be IO related. Use with extreme caution!

pymor.core.defaults.defaults_sid()[source]

Return a state id for pyMOR’s global defaults.

This method is used for the calculation of state ids of immutable objects and for cache key generation.


pymor.core.defaults.load_defaults_from_file(filename='./pymor_defaults.py')[source]

Loads default values defined in configuration file.

Suitable configuration files can be created via write_defaults_to_file. The file is loaded via Python’s exec function, so be very careful with configuration files you have not created your own. You have been warned!

Note that defaults should generally only be changed/loaded before state ids have been calculated. See this warning for details.

Parameters

filename
Path of the configuration file.

pymor.core.defaults.print_defaults(import_all=True, shorten_paths=2)[source]

Print all default values set in pyMOR.

Parameters

import_all
While print_defaults will always print all defaults defined in loaded configuration files or set via set_defaults, default values set in the function signature can only be printed after the modules containing these functions have been imported. If import_all is set to True, print_defaults will therefore first import all of pyMOR’s modules, to provide a complete lists of defaults.
shorten_paths
Shorten the paths of all default values by shorten_paths components. The last two path components will always be printed.

pymor.core.defaults.set_defaults(defaults)[source]

Set default values.

This method sets the default value of function arguments marked via the defaults decorator, overriding default values specified in the function signature or set earlier via load_defaults_from_file or previous set_defaults calls.

Note that defaults should generally only be changed/loaded before state ids have been calculated. See this warning for details.

Parameters

defaults
Dictionary of default values. Keys are the full paths of the default values (see defaults).

pymor.core.defaults.write_defaults_to_file(filename='./pymor_defaults.py', packages=('pymor', ))[source]

Write the currently set default values to a configuration file.

The resulting file is an ordinary Python script and can be modified by the user at will. It can be loaded in a later session using load_defaults_from_file.

Parameters

filename
Name of the file to write to.
packages
List of package names. To discover all default values that have been defined using the defaults decorator, write_defaults_to_file will recursively import all sub-modules of the named packages before creating the configuration file.
exceptions module
class pymor.core.exceptions.AccuracyError[source]

Bases: Exception

Is raised if the result of a computation is inaccurate

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.ConstError[source]

Bases: Exception

I get thrown when you try to add a new member to a locked class instance

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.ExtensionError[source]

Bases: Exception

Is raised if a (basis) extension algorithm fails.

This will mostly happen during a basis extension when the new snapshot is already in the span of the basis.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.GmshError[source]

Bases: Exception

Is raised when a Gmsh related error occurs.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.ImageCollectionError(op)[source]

Bases: Exception

Is raised when a pymor.algorithms.image.estimate_image fails for given operator.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.InversionError[source]

Bases: Exception

Is raised if an operator inversion algorithm fails.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.LinAlgError[source]

Bases: Exception

Is raised if a linear algebra operation fails.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.NewtonError[source]

Bases: Exception

Is raised if the Newton algorithm fails to converge.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.NoMatchingRuleError(obj)[source]

Bases: NotImplementedError

Methods

NotImplementedError __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.QtMissing(msg=None)[source]

Bases: ImportError

Raise me where having importable Qt bindings is non-optional

Methods

Exception __new__
BaseException with_traceback

Attributes

ImportError msg, name, path
BaseException args

class pymor.core.exceptions.RuleNotMatchingError[source]

Bases: NotImplementedError

Methods

NotImplementedError __new__
BaseException with_traceback

Attributes

BaseException args

class pymor.core.exceptions.SIDGenerationError[source]

Bases: Exception

Is raised when generate_sid fails.

Methods

Exception __new__
BaseException with_traceback

Attributes

BaseException args
interfaces module

This module provides base classes from which most classes in pyMOR inherit.

The purpose of these classes is to provide some common functionality for all objects in pyMOR. The most notable features provided by BasicInterface are the following:

  1. BasicInterface sets class UberMeta as metaclass which itself inherits from abc.ABCMeta. Thus it is possible to define interface classes with abstract methods using the abstractmethod decorator. There are also decorators for abstract class methods, static methods, and properties.
  2. Using metaclass magic, each class deriving from BasicInterface comes with its own logger instance accessible through its logger attribute. The logger prefix is automatically set to the class name.
  3. Logging can be disabled and re-enabled for each instance using the BasicInterface.disable_logging and BasicInterface.enable_logging methods.
  4. BasicInterface.uid provides a unique id for each instance. While id(obj) is only guaranteed to be unique among all living Python objects, BasicInterface.uid will be (almost) unique among all pyMOR objects that have ever existed, including previous runs of the application. This is achieved by building the id from a uuid4 which is newly created for each pyMOR run and a counter which is increased for any object that requests an uid.
  5. If not set by the user to another value, BasicInterface.name is set to the name of the object’s class.

ImmutableInterface derives from BasicInterface and adds the following functionality:

  1. Using more metaclass magic, each instance which derives from ImmutableInterface is locked after its __init__ method has returned. Each attempt to change one of its attributes raises an exception. Private attributes (of the form _name) are exempted from this rule.

  2. A unique state id for the instance can be calculated by calling generate_sid and is then stored as the object’s sid attribute. The state id is obtained by deterministically serializing the object’s state and then computing a checksum of the resulting byte stream.

  3. ImmutableInterface.sid_ignore can be set to a set of attribute names which should be excluded from state id calculation.

  4. ImmutableInterface.with_ can be used to create a copy of an instance with some changed attributes. E.g.

    obj.with_(a=x, b=y)
    

    creates a copy with the a and b attributes of obj set to x and y. (Note that in general a and b do not necessarily have to correspond to class attributes of obj; it is up to the implementor to interpret the provided arguments.) ImmutableInterface.with_arguments holds the set of allowed arguments.

    ImmutableInterface provides a default implementation of with_ which works by creating a new instance, passing the arguments of with_ to __init__. The missing __init__ arguments are taken from instance attributes of the same name.


class pymor.core.interfaces.BasicInterface[source]

Bases: object

Base class for most classes in pyMOR.

logger

A per-class instance of logging.Logger with the class name as prefix.

logging_disabled

True if logging has been disabled.

name

The name of the instance. If not set by the user, the name is set to the class name.

uid

A unique id for each instance. The uid is obtained by using UID and is unique for all pyMOR objects ever created.

disable_logging(doit=True)[source]

Disable logging output for this instance.

enable_logging(doit=True)[source]

Enable logging output for this instance.

classmethod has_interface_name()[source]

True if the class name ends with Interface. Used for introspection.

classmethod implementor_names(descend=False)[source]

For convenience I return a list of my implementor names instead of class objects

classmethod implementors(descend=False)[source]

I return a, potentially empty, list of my subclass-objects. If descend is True, I traverse my entire subclass hierarchy and return a flattened list.


class pymor.core.interfaces.ImmutableInterface[source]

Bases: pymor.core.interfaces.BasicInterface

Base class for immutable objects in pyMOR.

Instances of ImmutableInterface are immutable in the sense that after execution of __init__, any modification of a non-private attribute will raise an exception.

Warning

For instances of ImmutableInterface, the result of member function calls should be completely determined by the function’s arguments together with the object’s state id and the current state of pyMOR’s global defaults.

While, in principle, you are allowed to modify private members after instance initialization, this should never affect the outcome of future method calls. In particular, if you update any internal state after initialization, you have to ensure that this state is not affected by possible changes of the global defaults.

Also note that mutable private attributes will cause false cache misses when these attributes enter state id calculation. If your implementation uses such attributes, you should therefore add their names to the sid_ignore set.

add_with_arguments

Set of additional arguments for with_. (See with_arguments.)

sid

The objects state id. Only available after generate_sid has been called.

sid_ignore

Set of attributes not to include in state id calculation.

with_arguments

Set of allowed keyword arguments for with_. This is the union of the argument names of __init__ and the names specified via add_with_arguments.

__setattr__(key, value)[source]

depending on _locked state I delegate the setattr call to object or raise an Exception

generate_sid(debug=False)[source]

Generate a unique state id for the given object.

The generated state id is stored in the object’s sid attribute.

Parameters

debug
If True, produce some debugging output.

Returns

The generated state id.

with_(**kwargs)[source]

Returns a copy with changed attributes.

The default implementation is to create a new class instance with the given keyword arguments as arguments for __init__. Missing arguments are obtained form instance attributes with the same name.

Parameters

**kwargs
Names of attributes to change with their new values. Each attribute name has to be contained in with_arguments.

Returns

Copy of self with changed attributes.


class pymor.core.interfaces.ImmutableMeta(name, bases, namespace)[source]

Bases: pymor.core.interfaces.UberMeta

Metaclass for ImmutableInterface.

Methods

ABCMeta register, __instancecheck__, __subclasscheck__
type mro, __dir__, __prepare__, __sizeof__, __subclasses__
static __new__(cls, classname, bases, classdict)[source]

I copy docstrings from base class methods to deriving classes.

Copying of docstrings is disabled when the PYMOR_WITH_SPHINX environment variable is set to 1.


class pymor.core.interfaces.UID[source]

Bases: object

Provides unique, quickly computed ids by combining a session UUID4 with a counter.

Attributes

UID counter, prefix, uid

class pymor.core.interfaces.UberMeta(name, bases, namespace)[source]

Bases: abc.ABCMeta

Methods

UberMeta __new__
ABCMeta register, __instancecheck__, __subclasscheck__
type mro, __dir__, __prepare__, __sizeof__, __subclasses__
static __new__(cls, classname, bases, classdict)[source]

I copy docstrings from base class methods to deriving classes.

Copying of docstrings is disabled when the PYMOR_WITH_SPHINX environment variable is set to 1.


class pymor.core.interfaces.classinstancemethod(cls_meth)[source]

Bases: object

Methods

classinstancemethod instancemethod

pymor.core.interfaces.generate_sid(obj, debug=False)[source]

Generate a unique state id for the current state of the given object.

Parameters

obj
The object for which to compute the state sid.
debug
If True, produce some debug output.

Returns

The generated state id.

logger module

This module contains pyMOR’s logging facilities.

pyMOR’s logging facilities are based on the logging module of the Python standard library. To obtain a new logger object use getLogger. Logging can be configured via the set_log_format and set_log_levels methods.


class pymor.core.logger.ColoredFormatter[source]

Bases: logging.Formatter

A logging.Formatter that inserts tty control characters to color loglevel keyword output. Coloring can be disabled by setting the PYMOR_COLORS_DISABLE environment variable to 1.

Methods

ColoredFormatter format
Formatter converter, formatException, formatMessage, formatStack, formatTime, usesTime

Attributes

Formatter default_msec_format, default_time_format
format(record)[source]

Format the specified record as text.

The record’s attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage(). If the formatting string uses the time (as determined by a call to usesTime(), formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message.


class pymor.core.logger.DummyLogger[source]

Bases: object

Methods

DummyLogger block, critical, debug, error, exception, getChild, getEffectiveLevel, info, info2, info3, isEnabledFor, log, nop, warn, warning

Attributes

DummyLogger propagate

class pymor.core.logger.LogIndenter(logger, doit)[source]

Bases: object


pymor.core.logger.getLogger(module, level=None, filename='')[source]

Get the logger of the respective module for pyMOR’s logging facility.

Parameters

module
Name of the module.
level
If set, logger.setLevel(level) is called (see setLevel).
filename
If not empty, path of an existing file where everything logged will be written to.

Defaults

filename (see pymor.core.defaults)


pymor.core.logger.set_log_format(max_hierarchy_level=1, indent_blocks=True, block_timings=False)[source]

Set log levels for pyMOR’s logging facility.

Parameters

max_hierarchy_level
The number of components of the loggers name which are printed. (The first component is always stripped, the last component always preserved.)
indent_blocks
If True, indent log messages inside a code block started with with logger.block(...).
block_timings
If True, measure the duration of a code block started with with logger.block(...).

Defaults

max_hierarchy_level, indent_blocks, block_timings (see pymor.core.defaults)


pymor.core.logger.set_log_levels(levels=None)[source]

Set log levels for pyMOR’s logging facility.

Parameters

levels
Dict of log levels. Keys are names of loggers (see logging.getLogger), values are the log levels to set for the loggers of the given names (see setLevel).

Defaults

levels (see pymor.core.defaults)

pickle module

This module contains methods for object serialization.

Instead of importing serialization functions from Python’s pickle module directly, you should use the dump, dumps, load, loads functions defined here. In particular, these methods will use dumps_function to serialize function objects which cannot be pickled by Python’s standard methods. Note, however, pickling such methods should be avoided since the implementation of dumps_function uses non-portable implementation details of CPython to achieve its goals.


class pymor.core.pickle.Module(mod)[source]

Bases: object


pymor.core.pickle._global_names(code_object)[source]

Return all names in code_object.co_names which are used in a LOAD_GLOBAL statement.


pymor.core.pickle.dump(obj, file, protocol=None)[source]

pymor.core.pickle.dumps(obj, protocol=None)[source]

pymor.core.pickle.dumps_function(function)[source]

Tries hard to pickle a function object:

  1. The function’s code object is serialized using the marshal module.
  2. For all global names used in the function’s code object the corresponding object in the function’s global namespace is pickled. In case this object is a module, the modules __package__ name is pickled.
  3. All default arguments are pickled.
  4. All objects in the function’s closure are pickled.

Note that also this is heavily implementation specific and will probably only work with CPython. If possible, avoid using this method.


pymor.core.pickle.load(file)[source]

pymor.core.pickle.loads(str)[source]

pymor.core.pickle.loads_function(s)[source]

Restores a function serialized with dumps_function.

pymor.discretizations package
Submodules
basic module
class pymor.discretizations.basic.DiscretizationBase(operators=None, products=None, estimator=None, visualizer=None, cache_region=None, name=None, **kwargs)[source]

Bases: pymor.discretizations.interfaces.DiscretizationInterface

Base class for Discretizations providing some common functionality.

estimate(U, mu=None)[source]

Estimate the discretization error for a given solution.

The discretization error could be the error w.r.t. the analytical solution of the given problem or the model reduction error w.r.t. a corresponding high-dimensional Discretization.

Parameters

U
The solution obtained by solve.
mu
Parameter for which U has been obtained.

Returns

The estimated error.

visualize(U, **kwargs)[source]

Visualize a solution VectorArray U.

Parameters

U
The VectorArray from solution_space that shall be visualized.
kwargs
See docstring of self.visualizer.visualize.
with_(**kwargs)[source]

Returns a copy with changed attributes.

The default implementation is to create a new class instance with the given keyword arguments as arguments for __init__. Missing arguments are obtained form instance attributes with the same name.

Parameters

**kwargs
Names of attributes to change with their new values. Each attribute name has to be contained in with_arguments.

Returns

Copy of self with changed attributes.


class pymor.discretizations.basic.InstationaryDiscretization(T, initial_data, operator, rhs, mass=None, time_stepper=None, num_values=None, products=None, operators=None, parameter_space=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]

Bases: pymor.discretizations.basic.DiscretizationBase

Generic class for discretizations of instationary problems.

This class describes instationary problems given by the equations:

M * ∂_t u(t, μ) + L(u(μ), t, μ) = F(t, μ)
                        u(0, μ) = u_0(μ)

for t in [0,T], where L is a (possibly non-linear) time-dependent Operator, F is a time-dependent vector-like Operator, and u_0 the initial data. The mass Operator M is assumed to be linear, time-independent and Parameter-independent.

Parameters

T
The final time T.
initial_data
The initial data u_0. Either a VectorArray of length 1 or (for the Parameter-dependent case) a vector-like Operator (i.e. a linear Operator with source.dim == 1) which applied to NumpyVectorArray(np.array([1])) will yield the initial data for a given Parameter.
operator
The Operator L.
rhs
The right-hand side F.
mass
The mass Operator M. If None, the identity is assumed.
time_stepper
The time-stepper to be used by solve.
num_values
The number of returned vectors of the solution trajectory. If None, each intermediate vector that is calculated is returned.
products
A dict of product Operators defined on the discrete space the problem is posed on. For each product a corresponding norm is added as a method of the discretization.
operators
A dict of additional Operators associated with the discretization.
parameter_space
The ParameterSpace for which the discrete problem is posed.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, d) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, d, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the CacheRegion to use.
name
Name of the discretization.
T

The final time T.

initial_data

The intial data u_0 given by a vector-like Operator. The same as operators['initial_data'].

operator

The Operator L. The same as operators['operator'].

rhs

The right-hand side F. The same as operators['rhs'].

mass

The mass operator M. The same as operators['mass'].

time_stepper

The provided time-stepper.

operators

Dict of all Operators appearing in the discretization.

products

Dict of all product Operators associated with the discretization.

to_lti(output='output_functional')[source]

Convert discretization to LTISystem.

This method interprets the given discretization as an LTISystem in the following way:

- self.operator        -> A
self.rhs               -> B
self.operators[output] -> C
None                   -> D
self.mass              -> E

Parameters

output
Key in self.operators to use as output functional.
with_(**kwargs)[source]

Returns a copy with changed attributes.

The default implementation is to create a new class instance with the given keyword arguments as arguments for __init__. Missing arguments are obtained form instance attributes with the same name.

Parameters

**kwargs
Names of attributes to change with their new values. Each attribute name has to be contained in with_arguments.

Returns

Copy of self with changed attributes.


class pymor.discretizations.basic.StationaryDiscretization(operator, rhs, products=None, operators=None, parameter_space=None, estimator=None, visualizer=None, cache_region=None, name=None)[source]

Bases: pymor.discretizations.basic.DiscretizationBase

Generic class for discretizations of stationary problems.

This class describes discrete problems given by the equation:

L(u(μ), μ) = F(μ)

with a vector-like right-hand side F and a (possibly non-linear) operator L.

Note that even when solving a variational formulation where F is a functional and not a vector, F has to be specified as a vector-like Operator (mapping scalars to vectors). This ensures that in the complex case both L and F are anti-linear in the test variable.

Parameters

operator
The Operator L.
rhs
The vector F. Either a VectorArray of length 1 or a vector-like Operator.
products
A dict of inner product Operators defined on the discrete space the problem is posed on. For each product a corresponding norm is added as a method of the discretization.
operators
A dict of additional Operators associated with the discretization.
parameter_space
The ParameterSpace for which the discrete problem is posed.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, d) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, d, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the CacheRegion to use.
name
Name of the discretization.
operator

The Operator L. The same as operators['operator'].

rhs

The right-hand side F. The same as operators['rhs'].

operators

Dict of all Operators appearing in the discretization.

products

Dict of all product Operators associated with the discretization.

interfaces module
class pymor.discretizations.interfaces.DiscretizationInterface[source]

Bases: pymor.core.cache.CacheableInterface, pymor.parameters.base.Parametric

Interface for discretization objects.

A discretization object defines a discrete problem via its class and the Operators it contains. Furthermore, discretizations can be solved for a given Parameter resulting in a solution VectorArray.

solution_space

VectorSpace of the VectorArrays returned by solve.

linear

True if the discretization describes a linear problem.

operators

Dictionary of all Operators contained in the discretization (see GenericRBReductor for a usage example).

products

Same as Operators but for inner product operators associated with the discretization.

estimate(U, mu=None)[source]

Estimate the discretization error for a given solution.

The discretization error could be the error w.r.t. the analytical solution of the given problem or the model reduction error w.r.t. a corresponding high-dimensional Discretization.

Parameters

U
The solution obtained by solve.
mu
Parameter for which U has been obtained.

Returns

The estimated error.

solve(mu=None, **kwargs)[source]

Solve the discrete problem for the Parameter mu.

The result will be cached in case caching has been activated for the given discretization.

Parameters

mu
Parameter for which to solve.

Returns

The solution given as a VectorArray.

visualize(U, **kwargs)[source]

Visualize a solution VectorArray U.

Parameters

U
The VectorArray from solution_space that shall be visualized.
iosys module
class pymor.discretizations.iosys.InputOutputSystem(input_space, output_space, cont_time=True, cache_region='memory', name=None, **kwargs)[source]

Bases: pymor.discretizations.basic.DiscretizationBase

Base class for input-output systems.

bode(w)[source]

Evaluate the transfer function on the imaginary axis.

Parameters

w
Angular frequencies at which to compute the transfer function.

Returns

tfw
Transfer function values at frequencies in w, NumPy array of shape (len(w), self.p, self.m).
eval_dtf(s, mu=None)[source]

Evaluate the derivative of the transfer function.

eval_tf(s, mu=None)[source]

Evaluate the transfer function.

mag_plot(w, ax=None, ord=None, Hz=False, dB=False, **mpl_kwargs)[source]

Draw the magnitude Bode plot.

Parameters

w
Angular frequencies at which to evaluate the transfer function.
ax
Axis to which to plot. If not given, matplotlib.pyplot.gca is used.
ord
The order of the norm used to compute the magnitude (the default is the Frobenius norm).
Hz
Should the frequency be in Hz on the plot.
dB
Should the magnitude be in dB on the plot.
mpl_kwargs
Keyword arguments used in the matplotlib plot function.

Returns

out
List of matplotlib artists added.

class pymor.discretizations.iosys.InputStateOutputSystem(input_space, state_space, output_space, cont_time=True, cache_region='memory', name=None, **kwargs)[source]

Bases: pymor.discretizations.iosys.InputOutputSystem

Base class for input-output systems with state space.

__add__(other)[source]

Add two input-state-output systems.

__neg__()[source]

Negate input-state-output system.

__sub__(other)[source]

Subtract two input-state-output system.


class pymor.discretizations.iosys.LTISystem(A, B, C, D=None, E=None, cont_time=True, solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Bases: pymor.discretizations.iosys.InputStateOutputSystem

Class for linear time-invariant systems.

This class describes input-state-output systems given by

E \dot{x}(t) & = A x(t) + B u(t), \\
        y(t) & = C x(t) + D u(t),

if continuous-time, or

E x(k + 1) & = A x(k) + B u(k), \\
  y(k)     & = C x(k) + D u(k),

if discrete-time, where A, B, C, D, and E are linear operators.

Parameters

A
The Operator A.
B
The Operator B.
C
The Operator C.
D
The Operator D or None (then D is assumed to be zero).
E
The Operator E or None (then E is assumed to be identity).
cont_time
True if the system is continuous-time, otherwise False.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.
n

The order of the system.

A

The Operator A.

B

The Operator B.

C

The Operator C.

D

The Operator D.

E

The Operator E.

operators

Dict of all Operators appearing in the discretization.

__mul__(other)[source]

Multiply (cascade) two LTISystems.

eval_dtf(s)[source]

Evaluate the derivative of the transfer function.

The derivative of the transfer function at s is

-C (s E - A)^{-1} E (s E - A)^{-1} B.

Note

We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.

Parameters

s
Complex number.

Returns

dtfs
Derivative of transfer function evaluated at the complex number s, NumPy array of shape (self.p, self.m).
eval_tf(s)[source]

Evaluate the transfer function.

The transfer function at s is

C (s E - A)^{-1} B + D.

Note

We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.

Parameters

s
Complex number.

Returns

tfs
Transfer function evaluated at the complex number s, NumPy array of shape (self.p, self.m).
classmethod from_abcde_files(files_basename, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Create LTISystem from matrices stored in a .[ABCDE] files.

Parameters

files_basename
The basename of files containing A, B, C, and optionally D and E.
cont_time
True if the system is continuous-time, otherwise False.
input_id
Id of the input space.
state_id
Id of the state space.
output_id
Id of the output space.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.

Returns

lti
The LTISystem with operators A, B, C, D, and E.
classmethod from_files(A_file, B_file, C_file, D_file=None, E_file=None, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Create LTISystem from matrices stored in separate files.

Parameters

A_file
The name of the file (with extension) containing A.
B_file
The name of the file (with extension) containing B.
C_file
The name of the file (with extension) containing C.
D_file
None or the name of the file (with extension) containing D.
E_file
None or the name of the file (with extension) containing E.
cont_time
True if the system is continuous-time, otherwise False.
input_id
Id of the input space.
state_id
Id of the state space.
output_id
Id of the output space.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.

Returns

lti
The LTISystem with operators A, B, C, D, and E.
classmethod from_mat_file(file_name, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Create LTISystem from matrices stored in a .mat file.

Parameters

file_name
The name of the .mat file (extension .mat does not need to be included) containing A, B, C, and optionally D and E.
cont_time
True if the system is continuous-time, otherwise False.
input_id
Id of the input space.
state_id
Id of the state space.
output_id
Id of the output space.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.

Returns

lti
The LTISystem with operators A, B, C, D, and E.
classmethod from_matrices(A, B, C, D=None, E=None, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Create LTISystem from matrices.

Parameters

A
The NumPy array or SciPy spmatrix A.
B
The NumPy array or SciPy spmatrix B.
C
The NumPy array or SciPy spmatrix C.
D
The NumPy array or SciPy spmatrix D or None (then D is assumed to be zero).
E
The NumPy array or SciPy spmatrix E or None (then E is assumed to be identity).
cont_time
True if the system is continuous-time, otherwise False.
input_id
Id of the input space.
state_id
Id of the state space.
output_id
Id of the output space.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.

Returns

lti
The LTISystem with operators A, B, C, D, and E.
gramian(typ)[source]

Compute a Gramian.

Parameters

typ

The type of the Gramian:

  • 'c_lrcf': low-rank Cholesky factor of the controllability Gramian,
  • 'o_lrcf': low-rank Cholesky factor of the observability Gramian,
  • 'c_dense': dense controllability Gramian,
  • 'o_dense': dense observability Gramian,

Returns

If typ is 'c_lrcf' or 'o_lrcf', then the Gramian factor as a VectorArray from self.A.source. If typ is 'c_dense' or 'o_dense', then the Gramian as a NumPy array.

h2_norm()[source]

Compute the H2-norm of the LTISystem.

hankel_norm()[source]

Compute the Hankel-norm of the LTISystem.

hinf_norm(return_fpeak=False, ab13dd_equilibrate=False)[source]

Compute the H_infinity-norm of the LTISystem.

Parameters

return_fpeak
Should the frequency at which the maximum is achieved should be returned.
ab13dd_equilibrate
Should slycot.ab13dd use equilibration.

Returns

norm
H_infinity-norm.
fpeak
Frequency at which the maximum is achieved (if return_fpeak is True).
hsU()[source]

Left Hankel singular vectors.

Returns

Uh
NumPy array of left singluar vectors.
hsV()[source]

Right Hankel singular vectors.

Returns

Vh
NumPy array of right singluar vectors.
hsv()[source]

Hankel singular values.

Returns

sv
One-dimensional NumPy array of singular values.
poles()[source]

Compute system poles.


class pymor.discretizations.iosys.SecondOrderSystem(M, E, K, B, Cp, Cv=None, D=None, cont_time=True, solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Bases: pymor.discretizations.iosys.InputStateOutputSystem

Class for linear second order systems.

This class describes input-output systems given by

M \ddot{x}(t)
+ E \dot{x}(t)
+ K x(t)
& =
    B u(t), \\
y(t)
& =
    C_p x(t)
    + C_v \dot{x}(t)
    + D u(t),

if continuous-time, or

M x(k + 2)
+ E x(k + 1)
+ K x(k)
& =
    B u(k), \\
y(k)
& =
    C_p x(k)
    + C_v x(k + 1)
    + D u(k),

if discrete-time, where M, E, K, B, C_p, C_v, and D are linear operators.

Parameters

M
The Operator M.
E
The Operator E.
K
The Operator K.
B
The Operator B.
Cp
The Operator Cp.
Cv
The Operator Cv or None (then Cv is assumed to be zero).
D
The Operator D or None (then D is assumed to be zero).
cont_time
True if the system is continuous-time, otherwise False.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.
n

The order of the system (equal to M.source.dim).

M

The Operator M.

E

The Operator E.

K

The Operator K.

B

The Operator B.

Cp

The Operator Cp.

Cv

The Operator Cv.

D

The Operator D.

operators

Dictionary of all Operators contained in the discretization.

eval_dtf(s)[source]

Evaluate the derivative of the transfer function.

s C_v (s^2 M + s E + K)^{-1} B
- (C_p + s C_v) (s^2 M + s E + K)^{-1} (2 s M + E)
    (s^2 M + s E + K)^{-1} B.

Note

We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.

Parameters

s
Complex number.

Returns

dtfs
Derivative of transfer function evaluated at the complex number s, NumPy array of shape (self.p, self.m).
eval_tf(s)[source]

Evaluate the transfer function.

The transfer function at s is

(C_p + s C_v) (s^2 M + s E + K)^{-1} B + D.

Note

We assume that either the number of inputs or the number of outputs is much smaller than the order of the system.

Parameters

s
Complex number.

Returns

tfs
Transfer function evaluated at the complex number s, NumPy array of shape (self.p, self.m).
classmethod from_matrices(M, E, K, B, Cp, Cv=None, D=None, cont_time=True, input_id='INPUT', state_id='STATE', output_id='OUTPUT', solver_options=None, estimator=None, visualizer=None, cache_region='memory', name=None)[source]

Create a second order system from matrices.

Parameters

M
The NumPy array or SciPy spmatrix M.
E
The NumPy array or SciPy spmatrix E.
K
The NumPy array or SciPy spmatrix K.
B
The NumPy array or SciPy spmatrix B.
Cp
The NumPy array or SciPy spmatrix Cp.
Cv
The NumPy array or SciPy spmatrix Cv or None (then Cv is assumed to be zero).
D
The NumPy array or SciPy spmatrix D or None (then D is assumed to be zero).
cont_time
True if the system is continuous-time, otherwise False.
solver_options
The solver options to use to solve the Lyapunov equations.
estimator
An error estimator for the problem. This can be any object with an estimate(U, mu, discretization) method. If estimator is not None, an estimate(U, mu) method is added to the discretization which will call estimator.estimate(U, mu, self).
visualizer
A visualizer for the problem. This can be any object with a visualize(U, discretization, ...) method. If visualizer is not None, a visualize(U, *args, **kwargs) method is added to the discretization which forwards its arguments to the visualizer’s visualize method.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.

Returns

lti
The SecondOrderSystem with operators M, E, K, B, Cp, Cv, and D.
gramian(typ)[source]

Compute a second-order Gramian.

Parameters

typ

The type of the Gramian:

  • 'pc_lrcf': low-rank Cholesky factor of the position controllability Gramian,
  • 'vc_lrcf': low-rank Cholesky factor of the velocity controllability Gramian,
  • 'po_lrcf': low-rank Cholesky factor of the position observability Gramian,
  • 'vo_lrcf': low-rank Cholesky factor of the velocity observability Gramian,
  • 'pc_dense': dense position controllability Gramian,
  • 'vc_dense': dense velocity controllability Gramian,
  • 'po_dense': dense position observability Gramian,
  • 'vo_dense': dense velocity observability Gramian,

Returns

If typ is 'pc_lrcf', 'vc_lrcf', 'po_lrcf' or 'vo_lrcf', then the Gramian factor as a VectorArray from self.M.source. If typ is 'pc_dense', 'vc_dense', 'po_dense' or 'vo_dense', then the Gramian as a NumPy array.

h2_norm()[source]

Compute the H2-norm.

hankel_norm()[source]

Compute the Hankel-norm.

hinf_norm(return_fpeak=False, ab13dd_equilibrate=False)[source]

Compute the H_infinity-norm.

Parameters

return_fpeak
Should the frequency at which the maximum is achieved should be returned.
ab13dd_equilibrate
Should slycot.ab13dd use equilibration.

Returns

norm
H_infinity-norm.
fpeak
Frequency at which the maximum is achieved (if return_fpeak is True).
poles()[source]

Compute system poles.

psv()[source]

Position singular values.

Returns

One-dimensional NumPy array of singular values.

pvsv()[source]

Position-velocity singular values.

Returns

One-dimensional NumPy array of singular values.

to_lti()[source]

Return a first order representation.

The first order representation

\begin{bmatrix}
    I & 0 \\
    0 & M
\end{bmatrix}
\frac{\mathrm{d}}{\mathrm{d}t}\!
\begin{bmatrix}
    x(t) \\
    \dot{x}(t)
\end{bmatrix}
& =
\begin{bmatrix}
    0 & I \\
    -K & -E
\end{bmatrix}
\begin{bmatrix}
    x(t) \\
    \dot{x}(t)
\end{bmatrix}
+
\begin{bmatrix}
    0 \\
    B
\end{bmatrix}
u(t), \\
y(t)
& =
\begin{bmatrix}
    C_p & C_v
\end{bmatrix}
\begin{bmatrix}
    x(t) \\
    \dot{x}(t)
\end{bmatrix}
+ D u(t)

is returned.

Returns

lti
LTISystem equivalent to the second order system.
vpsv()[source]

Velocity-position singular values.

Returns

One-dimensional NumPy array of singular values.

vsv()[source]

Velocity singular values.

Returns

One-dimensional NumPy array of singular values.


class pymor.discretizations.iosys.TransferFunction(input_space, output_space, H, dH, cont_time=True, cache_region='memory', name=None)[source]

Bases: pymor.discretizations.iosys.InputOutputSystem

Class for systems represented by a transfer function.

This class describes input-output systems given by a transfer function H(s).

Parameters

input_space
The input VectorSpace. Typically NumpyVectorSpace(m, 'INPUT') where m is the number of inputs.
output_space
The output VectorSpace. Typically NumpyVectorSpace(p, 'OUTPUT') where p is the number of outputs.
H
The transfer function defined at least on the open right complex half-plane. H(s) is a NumPy array of shape (p, m).
dH
The complex derivative of H.
cont_time
True if the system is continuous-time, otherwise False.
cache_region
None or name of the cache region to use. See pymor.core.cache.
name
Name of the system.
tf

The transfer function.

dtf

The complex derivative of the transfer function.

eval_dtf(s)[source]

Evaluate the derivative of the transfer function.

eval_tf(s)[source]

Evaluate the transfer function.

mpi module
class pymor.discretizations.mpi.MPIDiscretization(obj_id, operators, products=None, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]

Bases: pymor.discretizations.basic.DiscretizationBase

Wrapper class for MPI distributed Discretizations.

Given a single-rank implementation of a Discretization, this wrapper class uses the event loop from pymor.tools.mpi to allow an MPI distributed usage of the Discretization. The underlying implementation needs to be MPI aware. In particular, the discretization’s solve method has to perform an MPI parallel solve of the discretization.

Note that this class is not intended to be instantiated directly. Instead, you should use mpi_wrap_discretization.

Parameters

obj_id
ObjectId of the local Discretization on each rank.
operators
Dictionary of all Operators contained in the discretization, wrapped for use on rank 0. Use mpi_wrap_discretization to automatically wrap all operators of a given MPI-aware Discretization.
products
See operators.
pickle_local_spaces
See MPIOperator.
space_type
See MPIOperator.

class pymor.discretizations.mpi.MPIVisualizer(d_obj_id)[source]

Bases: pymor.core.interfaces.ImmutableInterface


pymor.discretizations.mpi.mpi_wrap_discretization(local_discretizations, use_with=False, with_apply2=False, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]

Wrap MPI distributed local Discretizations to a global Discretization on rank 0.

Given MPI distributed local Discretizations referred to by the ObjectId local_discretizations, return a new Discretization which manages these distributed discretizations from rank 0. This is done by first wrapping all Operators of the Discretization using mpi_wrap_operator.

Alternatively, local_discretizations can be a callable (with no arguments) which is then called on each rank to instantiate the local Discretizations.

When use_with is False, an MPIDiscretization is instantiated with the wrapped operators. A call to solve will then use an MPI parallel call to the solve methods of the wrapped local Discretizations to obtain the solution. This is usually what you want when the actual solve is performed by an implementation in the external solver.

When use_with is True, with_ is called on the local Discretization on rank 0, to obtain a new Discretization with the wrapped MPI Operators. This is mainly useful when the local discretizations are generic Discretizations as in pymor.discretizations.basic and solve is implemented directly in pyMOR via operations on the contained Operators.

Parameters

local_discretizations
ObjectId of the local Discretizations on each rank or a callable generating the Discretizations.
use_with
See above.
with_apply2
See MPIOperator.
pickle_local_spaces
See MPIOperator.
space_type
See MPIOperator.
pymor.discretizers package
Submodules
cg module
pymor.discretizers.cg.discretize_instationary_cg(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None, preassemble=True)[source]

Discretizes an InstationaryProblem with a StationaryProblem as stationary part using finite elements.

Parameters

analytical_problem
The InstationaryProblem to discretize.
diameter
If not None, diameter is passed as an argument to the domain_discretizer.
domain_discretizer
Discretizer to be used for discretizing the analytical domain. This has to be a function domain_discretizer(domain_description, diameter, ...). If None, discretize_domain_default is used.
grid_type
If not None, this parameter is forwarded to domain_discretizer to specify the type of the generated Grid.
grid
Instead of using a domain discretizer, the Grid can also be passed directly using this parameter.
boundary_info
A BoundaryInfo specifying the boundary types of the grid boundary entities. Must be provided if grid is specified.
num_values
The number of returned vectors of the solution trajectory. If None, each intermediate vector that is calculated is returned.
time_stepper
The time-stepper to be used by solve.
nt
If time_stepper is not specified, the number of time steps for implicit Euler time stepping.
preassemble
If True, preassemble all operators in the resulting Discretization.

Returns

d
The Discretization that has been generated.
data

Dictionary with the following entries:

grid:The generated Grid.
boundary_info:The generated BoundaryInfo.
unassembled_d:In case preassemble is True, the generated Discretization before preassembling operators.

pymor.discretizers.cg.discretize_stationary_cg(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, grid=None, boundary_info=None, preassemble=True)[source]

Discretizes a StationaryProblem using finite elements.

Parameters

analytical_problem
The StationaryProblem to discretize.
diameter
If not None, diameter is passed as an argument to the domain_discretizer.
domain_discretizer
Discretizer to be used for discretizing the analytical domain. This has to be a function domain_discretizer(domain_description, diameter, ...). If None, discretize_domain_default is used.
grid_type
If not None, this parameter is forwarded to domain_discretizer to specify the type of the generated Grid.
grid
Instead of using a domain discretizer, the Grid can also be passed directly using this parameter.
boundary_info
A BoundaryInfo specifying the boundary types of the grid boundary entities. Must be provided if grid is specified.
preassemble
If True, preassemble all operators in the resulting Discretization.

Returns

d
The Discretization that has been generated.
data

Dictionary with the following entries:

grid:The generated Grid.
boundary_info:The generated BoundaryInfo.
unassembled_d:In case preassemble is True, the generated Discretization before preassembling operators.
disk module
pymor.discretizers.disk.discretize_instationary_from_disk(parameter_file, T=None, steps=None, u0=None, time_stepper=None)[source]

Load a linear affinely decomposed InstationaryDiscretization from file.

Similarly to discretize_stationary_from_disk, the discretization is specified via an ini.-file of the following form

[system-matrices]
L_1.mat: l_1(μ_1,...,μ_n)
L_2.mat: l_2(μ_1,...,μ_n)
...

[rhs-vectors]
F_1.mat: f_1(μ_1,...,μ_n)
F_2.mat: f_2(μ_1,...,μ_n)
...

[mass-matrix]
D.mat

[initial-solution]
u0: u0.mat

[parameter]
μ_1: a_1,b_1
...
μ_n: a_n,b_n

[products]
Prod1: P_1.mat
Prod2: P_2.mat
...

[time]
T: final time
steps: number of time steps

Parameters

parameter_file
Path to the ‘.ini’ parameter file.
T
End-time of desired solution. If None, the value specified in the parameter file is used.
steps
Number of time steps to. If None, the value specified in the parameter file is used.
u0
Initial solution. If None the initial solution is obtained from parameter file.
time_stepper
The desired time stepper to use. If None, implicit Euler time stepping is used.

Returns

d
The InstationaryDiscretization that has been generated.

pymor.discretizers.disk.discretize_stationary_from_disk(parameter_file)[source]

Load a linear affinely decomposed StationaryDiscretization from file.

The discretization is defined via an .ini-style file as follows

[system-matrices]
L_1.mat: l_1(μ_1,...,μ_n)
L_2.mat: l_2(μ_1,...,μ_n)
...

[rhs-vectors]
F_1.mat: f_1(μ_1,...,μ_n)
F_2.mat: f_2(μ_1,...,μ_n)
...

[parameter]
μ_1: a_1,b_1
...
μ_n: a_n,b_n

[products]
Prod1: P_1.mat
Prod2: P_2.mat
...

Here, L_1.mat, L_2.mat, …, F_1.mat, F_2.mat, … are files containing matrices L_1, L_2, … and vectors F_1.mat, F_2.mat, … which correspond to the affine components of the operator and right-hand side. The respective coefficient functionals, are given via the string expressions l_1(...), l_2(...), …, f_1(...) in the (scalar-valued) Parameter components w_1, …, w_n. The allowed lower and upper bounds a_i, b_i for the component μ_i are specified in the [parameters] section. The resulting operator and right-hand side are then of the form

L(μ) = l_1(μ)*L_1 + l_2(μ)*L_2+ ...
F(μ) = f_1(μ)*F_1 + f_2(μ)*L_2+ ...

In the [products] section, an optional list of inner products Prod1, Prod2, .. with corresponding matrices P_1.mat, P_2.mat can be specified.

Example:

[system-matrices]
matrix1.mat: 1.
matrix2.mat: 1. - theta**2

[rhs-vectors]
rhs.mat: 1.

[parameter]
theta: 0, 0.5

[products]
h1: h1.mat
l2: mass.mat

Parameters

parameter_file
Path to the parameter file.

Returns

d
The StationaryDiscretization that has been generated.
fv module
pymor.discretizers.fv.discretize_instationary_fv(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, num_flux='lax_friedrichs', lxf_lambda=1.0, eo_gausspoints=5, eo_intervals=1, grid=None, boundary_info=None, num_values=None, time_stepper=None, nt=None, preassemble=True)[source]

Discretizes an InstationaryProblem with a StationaryProblem as stationary part using the finite volume method.

Parameters

analytical_problem
The InstationaryProblem to discretize.
diameter
If not None, diameter is passed to the domain_discretizer.
domain_discretizer
Discretizer to be used for discretizing the analytical domain. This has to be a function domain_discretizer(domain_description, diameter, ...). If further arguments should be passed to the discretizer, use functools.partial. If None, discretize_domain_default is used.
grid_type
If not None, this parameter is forwarded to domain_discretizer to specify the type of the generated Grid.
num_flux
The numerical flux to use in the finite volume formulation. Allowed values are 'lax_friedrichs', 'engquist_osher', 'simplified_engquist_osher' (see pymor.operators.fv).
lxf_lambda
The stabilization parameter for the Lax-Friedrichs numerical flux (ignored, if different flux is chosen).
eo_gausspoints
Number of Gauss points for the Engquist-Osher numerical flux (ignored, if different flux is chosen).
eo_intervals
Number of sub-intervals to use for integration when using Engquist-Osher numerical flux (ignored, if different flux is chosen).
grid
Instead of using a domain discretizer, the Grid can also be passed directly using this parameter.
boundary_info
A BoundaryInfo specifying the boundary types of the grid boundary entities. Must be provided if grid is specified.
num_values
The number of returned vectors of the solution trajectory. If None, each intermediate vector that is calculated is returned.
time_stepper
The time-stepper to be used by solve.
nt
If time_stepper is not specified, the number of time steps for implicit Euler time stepping.
preassemble
If True, preassemble all operators in the resulting Discretization.

Returns

d
The Discretization that has been generated.
data

Dictionary with the following entries:

grid:The generated Grid.
boundary_info:The generated BoundaryInfo.
unassembled_d:In case preassemble is True, the generated Discretization before preassembling operators.

pymor.discretizers.fv.discretize_stationary_fv(analytical_problem, diameter=None, domain_discretizer=None, grid_type=None, num_flux='lax_friedrichs', lxf_lambda=1.0, eo_gausspoints=5, eo_intervals=1, grid=None, boundary_info=None, preassemble=True)[source]

Discretizes a StationaryProblem using the finite volume method.

Parameters

analytical_problem
The StationaryProblem to discretize.
diameter
If not None, diameter is passed as an argument to the domain_discretizer.
domain_discretizer
Discretizer to be used for discretizing the analytical domain. This has to be a function domain_discretizer(domain_description, diameter, ...). If None, discretize_domain_default is used.
grid_type
If not None, this parameter is forwarded to domain_discretizer to specify the type of the generated Grid.
num_flux
The numerical flux to use in the finite volume formulation. Allowed values are 'lax_friedrichs', 'engquist_osher', 'simplified_engquist_osher' (see pymor.operators.fv).
lxf_lambda
The stabilization parameter for the Lax-Friedrichs numerical flux (ignored, if different flux is chosen).
eo_gausspoints
Number of Gauss points for the Engquist-Osher numerical flux (ignored, if different flux is chosen).
eo_intervals
Number of sub-intervals to use for integration when using Engquist-Osher numerical flux (ignored, if different flux is chosen).
grid
Instead of using a domain discretizer, the Grid can also be passed directly using this parameter.
boundary_info
A BoundaryInfo specifying the boundary types of the grid boundary entities. Must be provided if grid is specified.
preassemble
If True, preassemble all operators in the resulting Discretization.

Returns

d
The Discretization that has been generated.
data

Dictionary with the following entries:

grid:The generated Grid.
boundary_info:The generated BoundaryInfo.
unassembled_d:In case preassemble is True, the generated Discretization before preassembling operators.
pymor.domaindescriptions package
Submodules
basic module
class pymor.domaindescriptions.basic.CircleDomain(domain=(0, 1))[source]

Bases: pymor.domaindescriptions.interfaces.DomainDescriptionInterface

Describes a domain with the topology of a circle, i.e. a line with identified end points.

Parameters

domain
List [x_l, x_r] providing the left and right endpoint.
domain
__repr__()[source]

Return repr(self).


class pymor.domaindescriptions.basic.CylindricalDomain(domain=([0, 0], [1, 1]), top='dirichlet', bottom='dirichlet')[source]

Bases: pymor.domaindescriptions.interfaces.DomainDescriptionInterface

Describes a cylindrical domain.

Boundary types can be associated edgewise.

Parameters

domain
List of two points defining the lower-left and upper-right corner of the domain. The left and right edge are identified.
top
The boundary type of the top edge.
bottom
The boundary type of the bottom edge.

Attributes

CylindricalDomain bottom, diameter, dim, domain, height, lower_left, top, upper_right, volume, width
DomainDescriptionInterface boundary_types, has_dirichlet, has_neumann, has_robin
ImmutableInterface add_with_arguments, sid, sid_ignore, with_arguments
BasicInterface logger, logging_disabled, name, uid
domain
top
bottom
__repr__()[source]

Return repr(self).


class pymor.domaindescriptions.basic.LineDomain(domain=(0, 1), left='dirichlet', right='dirichlet')[source]

Bases: pymor.domaindescriptions.interfaces.DomainDescriptionInterface

Describes an interval domain.

Boundary types can be associated edgewise.

Parameters

domain
List [x_l, x_r] providing the left and right endpoint.
left
The boundary type of the left endpoint.
right
The boundary type of the right endpoint.
domain
left
right
__repr__()[source]

Return repr(self).


class pymor.domaindescriptions.basic.RectDomain(domain=([0, 0], [1, 1]), left='dirichlet', right='dirichlet', top='dirichlet', bottom='dirichlet')[source]

Bases: pymor.domaindescriptions.interfaces.DomainDescriptionInterface

Describes a rectangular domain.

Boundary types can be associated edgewise.

Parameters

domain
List of two points defining the lower-left and upper-right corner of the domain.
left
The boundary type of the left edge.
right
The boundary type of the right edge.
top
The boundary type of the top edge.
bottom
The boundary type of the bottom edge.

Attributes

RectDomain bottom, diameter, dim, domain, height, left, lower_left, right, top, upper_right, volume, width
DomainDescriptionInterface boundary_types, has_dirichlet, has_neumann, has_robin
ImmutableInterface add_with_arguments, sid, sid_ignore, with_arguments
BasicInterface logger, logging_disabled, name, uid
domain
left
right
top
bottom
__repr__()[source]

Return repr(self).


class pymor.domaindescriptions.basic.TorusDomain(domain=([0, 0], [1, 1]))[source]

Bases: pymor.domaindescriptions.interfaces.DomainDescriptionInterface

Describes a domain with the topology of a torus.

Parameters

domain
List of two points defining the lower-left and upper-right corner of the domain. The left and right edge are identified, as well as the bottom and top edge

Attributes

TorusDomain diameter, dim, domain, height, lower_left, upper_right, volume, width
DomainDescriptionInterface boundary_types, has_dirichlet, has_neumann, has_robin
ImmutableInterface add_with_arguments, sid, sid_ignore, with_arguments
BasicInterface logger, logging_disabled, name, uid
domain
__repr__()[source]

Return repr(self).

interfaces module
class pymor.domaindescriptions.interfaces.DomainDescriptionInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface

Describes a geometric domain along with its boundary.

dim

The dimension of the domain

boundary_types

Set of boundary types the domain has.

polygonal module
class pymor.domaindescriptions.polygonal.CircularSectorDomain(angle, radius, arc='dirichlet', radii='dirichlet', num_points=100)[source]

Bases: pymor.domaindescriptions.polygonal.PolygonalDomain

Describes a circular sector domain of variable radius.

Parameters

angle
The angle between 0 and 2*pi of the circular sector.
radius
The radius of the circular sector.
arc
The boundary type of the arc.
radii
The boundary type of the two radii.
num_points
The number of points of the polygonal chain approximating the circular boundary.
angle
radius
arc
radii
num_points
__repr__()[source]

Return repr(self).


class pymor.domaindescriptions.polygonal.DiscDomain(radius, boundary='dirichlet', num_points=100)[source]

Bases: pymor.domaindescriptions.polygonal.PolygonalDomain

Describes a disc domain of variable radius.

Parameters

radius
The radius of the disc.
boundary
The boundary type of the boundary.
num_points
The number of points of the polygonal chain approximating the boundary.
radius
boundary
num_points
__repr__()[source]

Return repr(self).


class pymor.domaindescriptions.polygonal.PolygonalDomain(points, boundary_types, holes=None)[source]

Bases: pymor.domaindescriptions.interfaces.DomainDescriptionInterface

Describes a domain with a polygonal boundary and polygonal holes inside the domain.

Parameters

points
List of points [x_0, x_1] that describe the polygonal chain that bounds the domain.
boundary_types
Either a dictionary {boundary_type: [i_0, ...], boundary_type: [j_0, ...], ...} with i_0, ... being the ids of boundary segments for a given boundary type (0 is the line connecting point 0 to 1, 1 is the line connecting point 1 to 2 etc.), or a function that returns the boundary type for a given coordinate.
holes
List of lists of points that describe the polygonal chains that bound the holes inside the domain.
points
boundary_types
holes
__repr__()[source]

Return repr(self).

pymor.domaindiscretizers package
Submodules
default module
pymor.domaindiscretizers.default.discretize_domain_default(domain_description, diameter=0.01, grid_type=None)[source]

Mesh a DomainDescription using an appropriate default implementation.

This method can discretize the following DomainDescriptions:

Parameters

domain_description
A DomainDescription of the domain to mesh.
diameter
Maximal diameter of the codim-0 entities of the generated Grid.
grid_type
The class of the Grid which is to be constructed. If None, a default choice is made according to the table above.

Returns

grid
The generated Grid.
boundary_info
The generated BoundaryInfo.
gmsh module
pymor.domaindiscretizers.gmsh.discretize_gmsh(domain_description=None, geo_file=None, geo_file_path=None, msh_file_path=None, mesh_algorithm='del2d', clscale=1.0, options='', refinement_steps=0)[source]

Mesh a DomainDescription or an already existing Gmsh GEO-file using the Gmsh mesher.

Parameters

domain_description
A DomainDescription of the PolygonalDomain or RectDomain to discretize. Has to be None when geo_file is given.
geo_file
File handle of the Gmsh Geo-file to discretize. Has to be None when domain_description is given.
geo_file_path
Path of the created Gmsh GEO-file. When meshing a PolygonalDomain or RectDomain and geo_file_path is None, a temporary file will be created. If geo_file is specified, this is ignored and the path to geo_file will be used.
msh_file_path
Path of the created Gmsh MSH-file. If None, a temporary file will be created.
mesh_algorithm
The mesh generation algorithm to use (meshadapt, del2d, front2d).
clscale
Mesh element size scaling factor.
options
Other options to control the meshing procedure of Gmsh. See http://geuz.org/gmsh/doc/texinfo/gmsh.html#Command_002dline-options for all available options.
refinement_steps
Number of refinement steps to do after the initial meshing.

Returns

grid
The generated GmshGrid.
boundary_info
The generated GmshBoundaryInfo.
pymor.functions package
Submodules
basic module
class pymor.functions.basic.ConstantFunction(value=array(1.), dim_domain=1, name=None)[source]

Bases: pymor.functions.basic.FunctionBase

A constant Function

f: R^d -> R^shape(c), f(x) = c

Parameters

value
The constant c.
dim_domain
The dimension d.
name
The name of the function.
__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

evaluate(x, mu=None)[source]

Evaluate the function for given argument x and Parameter mu.


class pymor.functions.basic.ExpressionFunction(expression, dim_domain=1, shape_range=(), parameter_type=None, values=None, name=None)[source]

Bases: pymor.functions.basic.GenericFunction

Turns a Python expression given as a string into a Function.

Some NumPy arithmetic functions like ‘sin’, ‘log’, ‘min’ are supported. For a full list see the functions class attribute.

Warning

eval is used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction!

Parameters

expression
A Python expression of one variable x and a parameter mu given as a string.
dim_domain
The dimension of the domain.
shape_range
The shape of the values returned by the expression.
parameter_type
The ParameterType the expression accepts.
values
Dictionary of additional constants that can be used in expression with their corresponding value.
name
The name of the function.
__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).


class pymor.functions.basic.FunctionBase[source]

Bases: pymor.functions.interfaces.FunctionInterface

Base class for Functions providing some common functionality.


class pymor.functions.basic.GenericFunction(mapping, dim_domain=1, shape_range=(), parameter_type=None, name=None)[source]

Bases: pymor.functions.basic.FunctionBase

Wrapper making an arbitrary Python function between NumPy arrays a proper Function.

Note that a GenericFunction can only be pickled if the function it is wrapping can be pickled (cf. dumps_function). For this reason, it is usually preferable to use ExpressionFunction instead of GenericFunction.

Parameters

mapping

The function to wrap. If parameter_type is None, the function is of the form mapping(x). If parameter_type is not None, the function has to have the signature mapping(x, mu). Moreover, the function is expected to be vectorized, i.e.:

mapping(x).shape == x.shape[:-1] + shape_range.
dim_domain
The dimension of the domain.
shape_range
The shape of the values returned by the mapping.
parameter_type
The ParameterType the mapping accepts.
name
The name of the function.
__str__()[source]

Return str(self).

evaluate(x, mu=None)[source]

Evaluate the function for given argument x and Parameter mu.


class pymor.functions.basic.LincombFunction(functions, coefficients, name=None)[source]

Bases: pymor.functions.basic.FunctionBase

A Function representing a linear combination of Functions.

The linear coefficients can be provided either as scalars or as ParameterFunctionals.

Parameters

functions
List of Functions whose linear combination is formed.
coefficients
A list of linear coefficients. A linear coefficient can either be a fixed number or a ParameterFunctional.
name
Name of the function.
functions
coefficients
evaluate(x, mu=None)[source]

Evaluate the function for given argument x and Parameter mu.

evaluate_coefficients(mu)[source]

Compute the linear coefficients for a given Parameter mu.


class pymor.functions.basic.ProductFunction(functions, name=None)[source]

Bases: pymor.functions.basic.FunctionBase

A Function representing a product of Functions.

Parameters

functions
List of Functions whose product is formed.
name
Name of the function.
functions
evaluate(x, mu=None)[source]

Evaluate the function for given argument x and Parameter mu.

bitmap module
class pymor.functions.bitmap.BitmapFunction(filename, bounding_box=None, range=None)[source]

Bases: pymor.functions.basic.FunctionBase

Define a 2D Function via a grayscale image.

Parameters

filename
Path of the image representing the function.
bounding_box
Lower left and upper right coordinates of the domain of the function.
range
A pixel of value p is mapped to (p / 255.) * range[1] + range[0].
evaluate(x, mu=None)[source]

Evaluate the function for given argument x and Parameter mu.

interfaces module
class pymor.functions.interfaces.FunctionInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface, pymor.parameters.base.Parametric

Interface for Parameter dependent analytical functions.

Every Function is a map of the form

f(μ): Ω ⊆ R^d -> R^(shape_range)

The returned values are NumPy arrays of arbitrary (but fixed) shape. Note that NumPy distinguishes between one-dimensional arrays of length 1 (with shape (1,)) and zero-dimensional scalar arrays (with shape ()). In pyMOR, we usually expect scalar-valued functions to have shape_range == ().

While the function might raise an error if it is evaluated for an argument not in the domain Ω, the exact behavior is left undefined.

Functions are vectorized in the sense, that if x.ndim == k, then

f(x, μ)[i0, i1, ..., i(k-2)] == f(x[i0, i1, ..., i(k-2)], μ).

In particular, f(x, μ).shape == x.shape[:-1] + shape_range.

dim_domain

The dimension d > 0.

shape_range

The shape of the function values.

__call__(x, mu=None)[source]

Shorthand for evaluate.

evaluate(x, mu=None)[source]

Evaluate the function for given argument x and Parameter mu.

pymor.grids package
Submodules
_unstructured module
boundaryinfos module
class pymor.grids.boundaryinfos.AllDirichletBoundaryInfo(grid)[source]

Bases: pymor.grids.interfaces.BoundaryInfoInterface

BoundaryInfo where the boundary type ‘dirichlet’ is attached to each boundary entity.

mask(boundary_type, codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to the boundary type boundary_type.


class pymor.grids.boundaryinfos.BoundaryInfoFromIndicators(grid, indicators, assert_unique_type=None, assert_some_type=None)[source]

Bases: pymor.grids.interfaces.BoundaryInfoInterface

BoundaryInfo where the boundary types are determined by indicator functions.

Parameters

grid
The Grid to which the BoundaryInfo is associated.
indicators
Dict where each key is a boundary type and the corresponding value is a boolean valued function defined on the analytical domain which indicates if a point belongs to a boundary of the given boundary type (the indicator functions must be vectorized).
mask(boundary_type, codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to the boundary type boundary_type.


class pymor.grids.boundaryinfos.EmptyBoundaryInfo(grid)[source]

Bases: pymor.grids.interfaces.BoundaryInfoInterface

BoundaryInfo with no boundary types attached to any boundary.

mask(boundary_type, codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to the boundary type boundary_type.


class pymor.grids.boundaryinfos.SubGridBoundaryInfo(subgrid, grid, grid_boundary_info, new_boundary_type=None)[source]

Bases: pymor.grids.interfaces.BoundaryInfoInterface

Derives a BoundaryInfo for a SubGrid.

Parameters

subrid
The SubGrid for which a BoundaryInfo is created.
grid
The parent Grid.
grid_boundary_info
The BoundaryInfo of the parent Grid from which to derive the BoundaryInfo
new_boundary_type
The boundary type which is assigned to the new boundaries of subgrid. If None, no boundary type is assigned.
mask(boundary_type, codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to the boundary type boundary_type.

constructions module
pymor.grids.constructions.flatten_grid(grid)[source]

This method is used by our visualizers to render n-dimensional grids which cannot be embedded into R^n by duplicating vertices which would have to be mapped to multiple points at once (think of grids on rectangular domains with identified edges).

Parameters

grid
The Grid to flatten.

Returns

subentities
The subentities(0, grid.dim) relation for the flattened grid.
coordinates
The coordinates of the codim-grid.dim entities.
entity_map
Maps the indices of the codim-grid.dim entities of the flattened grid to the indices of the corresponding entities in the original grid.
defaultimpl module
class pymor.grids.defaultimpl.AffineGridDefaultImplementations[source]

Bases: object

Provides default implementations for AffineGrids.


class pymor.grids.defaultimpl.ConformalTopologicalGridDefaultImplementations[source]

Bases: object

Provides default informations for ConformalTopologicalGrids.


class pymor.grids.defaultimpl.ReferenceElementDefaultImplementations[source]

Bases: object

Provides default implementations for ReferenceElements.

gmsh module
class pymor.grids.gmsh.GmshBoundaryInfo(grid, sections)[source]

Bases: pymor.grids.interfaces.BoundaryInfoInterface

BoundaryInfo for a GmshGrid.

Parameters

grid
The corresponding GmshGrid.
sections
Parsed sections of the MSH-file as returned by load_gmsh.
mask(boundary_type, codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to the boundary type boundary_type.


class pymor.grids.gmsh.GmshGrid(sections)[source]

Bases: pymor.grids.unstructured.UnstructuredTriangleGrid

An UnstructuredTriangleGrid built from an existing Gmsh MSH-file.

Parameters

sections
Parsed sections of the MSH-file as returned by load_gmsh.
__str__()[source]

Return str(self).


pymor.grids.gmsh.load_gmsh(gmsh_file)[source]

Parse a Gmsh file and create a corresponding GmshGrid and GmshBoundaryInfo.

Parameters

gmsh_file
File handle of the Gmsh MSH-file.

Returns

grid
The generated GmshGrid.
boundary_info
The generated GmshBoundaryInfo.
interfaces module
class pymor.grids.interfaces.AffineGridInterface[source]

Bases: pymor.grids.defaultimpl.AffineGridDefaultImplementations, pymor.grids.interfaces.ConformalTopologicalGridInterface

Topological grid with geometry where each codim-0 entity is affinely mapped to the same ReferenceElement.

The grid is completely determined via the subentity relation given by subentities and the embeddings given by embeddings. In addition, only size and reference_element have to be implemented. Cached default implementations for all other methods are provided by AffineGridDefaultImplementations.

bounding_box()[source]

returns a (2, dim)-shaped array containing lower/upper bounding box coordinates.

centers(codim)[source]

retval[e] is the barycenter of the codim-codim entity with global index e.

diameters(codim)[source]

retval[e] is the diameter of the codim-codim entity with global index e.

embeddings(codim)[source]

Returns tuple (A, B) where A[e] and B[e] are the linear part and the translation part of the map from the reference element of e to e.

For codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entity e_0 of e with lowest global index and composing it with the subentity_embedding of e into e_0 determined by the reference element.

integration_elements(codim)[source]

retval[e] is given as sqrt(det(A^T*A)), where A = embeddings(codim)[0][e].

jacobian_inverse_transposed(codim)[source]

retval[e] is the transposed (pseudo-)inverse of the Jacobian of embeddings(codim)[e].

quadrature_points(codim, order=None, npoints=None, quadrature_type='default')[source]

retval[e] is an array of quadrature points in global coordinates for the codim-codim entity with global index e.

The quadrature is of order order or has npoints integration points. To integrate a function f over e one has to form

np.dot(f(quadrature_points(codim, order)[e]), reference_element(codim).quadrature(order)[1]) *
integration_elements(codim)[e].  # NOQA
reference_element(codim)[source]

The ReferenceElement of the codim-codim entities.

subentities(codim, subentity_codim)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

The ordering of subentities(0, subentity_codim)[e] has to correspond, w.r.t. the embedding of e, to the local ordering inside the reference element.

For codim > 0, we provide a default implementation by calculating the subentities of e as follows:

  1. Find the codim-1 parent entity e_0 of e with minimal global index
  2. Lookup the local indices of the subentities of e inside e_0 using the reference element.
  3. Map these local indices to global indices using subentities(codim - 1, subentity_codim).

This procedures assures that subentities(codim, subentity_codim)[e] has the right ordering w.r.t. the embedding determined by e_0, which agrees with what is returned by embeddings(codim)

unit_outer_normals()[source]

retval[e,i] is the unit outer normal to the i-th codim-1 subentity of the codim-0 entitiy with global index e.

volumes(codim)[source]

retval[e] is the (dim-codim)-dimensional volume of the codim-codim entity with global index e.

volumes_inverse(codim)[source]

retval[e] = 1 / volumes(codim)[e].


class pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterface[source]

Bases: pymor.grids.interfaces.AffineGridInterface

AffineGrid with an additional orthogonal_centers method.

orthogonal_centers()[source]

retval[e] is a point inside the codim-0 entity with global index e such that the line segment from retval[e] to retval[e2] is always orthogonal to the codim-1 entity shared by the codim-0 entities with global index e and e2.

(This is mainly useful for gradient approximation in finite volume schemes.)


class pymor.grids.interfaces.BoundaryInfoInterface[source]

Bases: pymor.core.cache.CacheableInterface

Provides boundary types for the boundaries of a given ConformalTopologicalGrid.

For every boundary type and codimension a mask is provided, marking grid entities of the respective type and codimension by their global index.

boundary_types

set of all boundary types the grid has.

mask(boundary_type, codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to the boundary type boundary_type.

no_boundary_type_mask(codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to no boundary type.

unique_boundary_type_mask(codim)[source]

retval[i] is True if the codim-codim entity of global index i is associated to one and only one boundary type.


class pymor.grids.interfaces.ConformalTopologicalGridInterface[source]

Bases: pymor.grids.defaultimpl.ConformalTopologicalGridDefaultImplementations, pymor.core.cache.CacheableInterface

A topological grid without hanging nodes.

The grid is completely determined via the subentity relation given by subentities. In addition, only size has to be implemented, cached default implementations for all other methods are provided by ConformalTopologicalGridDefaultImplementations.

dim

The dimension of the grid.

boundaries(codim)[source]

Returns the global indices of all codim-codim boundary entities.

By definition, a codim-1 entity is a boundary entity if it has only one codim-0 superentity. For codim != 1, a codim-codim entity is a boundary entity if it has a codim-1 sub/super-entity.

boundary_mask(codim)[source]

retval[e] is true iff the codim-codim entity with global index e is a boundary entity.

By definition, a codim-1 entity is a boundary entity if it has only one codim-0 superentity. For codim != 1, a codim-codim entity is a boundary entity if it has a codim-1 sub/super-entity.

neighbours(codim, neighbour_codim, intersection_codim=None)[source]

retval[e,n] is the global index of the n-th codim-neighbour_codim entitiy of the codim-codim entity e that shares with e a subentity of codimension intersection_codim.

If intersection_codim == None, it is set to codim + 1 if codim == neighbour_codim and to min(codim, neighbour_codim) otherwise.

The default implementation is to compute the result from subentities(codim, intersection_codim) and superentities(intersection_codim, neihbour_codim).

size(codim)[source]

The number of entities of codimension codim.

subentities(codim, subentity_codim)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

Only subentities(codim, codim+1) has to be implemented; a default implementation is provided which evaluates subentities(codim, subentity_codim) by computing the transitive closure of subentities(codim, codim+1).

superentities(codim, superentity_codim)[source]

retval[e,s] is the global index of the s-th codim-superentity_codim superentity of the codim-codim entity with global index e.

retval[e] is sorted by global index.

The default implementation is to compute the result from subentities(superentity_codim, codim).

superentity_indices(codim, superentity_codim)[source]

retval[e,s] is the local index of the codim-codim entity e in the codim-superentity_codim superentity superentities(codim, superentity_codim)[e,s].


class pymor.grids.interfaces.ReferenceElementInterface[source]

Bases: pymor.grids.defaultimpl.ReferenceElementDefaultImplementations, pymor.core.cache.CacheableInterface

Defines a reference element.

All reference elements have the property that all subentities of a given codimension are of the same type. I.e. a three-dimensional reference element cannot have triangles and rectangles as faces at the same time.

dim

The dimension of the reference element

volume

The volume of the reference element

__call__(codim)[source]

Returns the reference element of the codim-codim subentities.

center()[source]

Coordinates of the barycenter.

mapped_diameter(A)[source]

The diameter of the reference element after transforming it with the matrix A (vectorized).

quadrature(order=None, npoints=None, quadrature_type='default')[source]

Returns tuple (P, W) where P is an array of quadrature points with corresponding weights W.

The quadrature is of order order or has npoints integration points.

quadrature_info()[source]

Returns a tuple of dicts (O, N) where O[quadrature_type] is a list of orders which are implemented for quadrature_type and N[quadrature_type] is a list of the corresponding numbers of integration points.

size(codim)[source]

Number of subentities of codimension codim.

sub_reference_element(codim)[source]

Returns the reference element of the codim-codim subentities.

subentities(codim, subentity_codim)[source]

subentities(c,sc)[i,j] is, with respect to the indexing inside the reference element, the index of the j-th codim-subentity_codim subentity of the i-th codim-codim subentity of the reference element.

subentity_embedding(subentity_codim)[source]

Returns a tuple (A, B) which defines the embedding of the codim-subentity_codim subentities into the reference element.

For subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1) and sub_reference_element(subentity_codim - 1).subentity_embedding(1) choosing always the superentity with smallest index.

unit_outer_normals()[source]

retval[e] is the unit outer-normal vector to the codim-1 subentity with index e.

oned module
class pymor.grids.oned.OnedGrid(domain=(0, 1), num_intervals=4, identify_left_right=False)[source]

Bases: pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterface

One-dimensional Grid on an interval.

Parameters

domain
Tuple (left, right) containing the left and right boundary of the domain.
num_intervals
The number of codim-0 entities.
__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

bounding_box()[source]

returns a (2, dim)-shaped array containing lower/upper bounding box coordinates.

embeddings(codim)[source]

Returns tuple (A, B) where A[e] and B[e] are the linear part and the translation part of the map from the reference element of e to e.

For codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entity e_0 of e with lowest global index and composing it with the subentity_embedding of e into e_0 determined by the reference element.

orthogonal_centers()[source]

retval[e] is a point inside the codim-0 entity with global index e such that the line segment from retval[e] to retval[e2] is always orthogonal to the codim-1 entity shared by the codim-0 entities with global index e and e2.

(This is mainly useful for gradient approximation in finite volume schemes.)

size(codim=0)[source]

The number of entities of codimension codim.

subentities(codim, subentity_codim)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

The ordering of subentities(0, subentity_codim)[e] has to correspond, w.r.t. the embedding of e, to the local ordering inside the reference element.

For codim > 0, we provide a default implementation by calculating the subentities of e as follows:

  1. Find the codim-1 parent entity e_0 of e with minimal global index
  2. Lookup the local indices of the subentities of e inside e_0 using the reference element.
  3. Map these local indices to global indices using subentities(codim - 1, subentity_codim).

This procedures assures that subentities(codim, subentity_codim)[e] has the right ordering w.r.t. the embedding determined by e_0, which agrees with what is returned by embeddings(codim)

visualize(U, codim=2, **kwargs)[source]

Visualize scalar data associated to the grid as a patch plot.

Parameters

U
NumPy array of the data to visualize. If U.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of NumPy arrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
kwargs
See visualize_patch
rect module
class pymor.grids.rect.RectGrid(num_intervals=(2, 2), domain=([0, 0], [1, 1]), identify_left_right=False, identify_bottom_top=False)[source]

Bases: pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterface

Basic implementation of a rectangular Grid on a rectangular domain.

The global face, edge and vertex indices are given as follows

x1
^
|

6--10---7--11---8
|       |       |
3   2   4   3   5
|       |       |
3---8---4---9---5
|       |       |
0   0   1   1   2
|       |       |
0---6---1---7---2  --> x0

Parameters

num_intervals
Tuple (n0, n1) determining a grid with n0 x n1 codim-0 entities.
domain
Tuple (ll, ur) where ll defines the lower left and ur the upper right corner of the domain.
identify_left_right
If True, the left and right boundaries are identified, i.e. the left-most codim-0 entities become neighbors of the right-most codim-0 entities.
identify_bottom_top
If True, the bottom and top boundaries are identified, i.e. the bottom-most codim-0 entities become neighbors of the top-most codim-0 entities.
__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

bounding_box()[source]

returns a (2, dim)-shaped array containing lower/upper bounding box coordinates.

embeddings(codim=0)[source]

Returns tuple (A, B) where A[e] and B[e] are the linear part and the translation part of the map from the reference element of e to e.

For codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entity e_0 of e with lowest global index and composing it with the subentity_embedding of e into e_0 determined by the reference element.

global_to_structured(codim)[source]

Returns an array which maps global codim-codim indices to structured indices.

I.e. if GTS = global_to_structured(codim) and STG = structured_to_global(codim), then STG[GTS[:, 0], GTS[:, 1]] == numpy.arange(size(codim)).

orthogonal_centers()[source]

retval[e] is a point inside the codim-0 entity with global index e such that the line segment from retval[e] to retval[e2] is always orthogonal to the codim-1 entity shared by the codim-0 entities with global index e and e2.

(This is mainly useful for gradient approximation in finite volume schemes.)

size(codim=0)[source]

The number of entities of codimension codim.

structured_to_global(codim)[source]

Returns an NumPy array which maps structured indices to global codim-codim indices.

In other words structured_to_global(codim)[i, j] is the global index of the i-th in x0-direction and j-th in x1-direction codim-codim entity of the grid.

subentities(codim, subentity_codim)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

The ordering of subentities(0, subentity_codim)[e] has to correspond, w.r.t. the embedding of e, to the local ordering inside the reference element.

For codim > 0, we provide a default implementation by calculating the subentities of e as follows:

  1. Find the codim-1 parent entity e_0 of e with minimal global index
  2. Lookup the local indices of the subentities of e inside e_0 using the reference element.
  3. Map these local indices to global indices using subentities(codim - 1, subentity_codim).

This procedures assures that subentities(codim, subentity_codim)[e] has the right ordering w.r.t. the embedding determined by e_0, which agrees with what is returned by embeddings(codim)

vertex_coordinates(dim)[source]

Returns an array of the x_dim coordinates of the grid vertices.

I.e.

centers(2)[structured_to_global(2)[i, j]] == np.array([vertex_coordinates(0)[i], vertex_coordinates(1)[j]])
visualize(U, codim=2, **kwargs)[source]

Visualize scalar data associated to the grid as a patch plot.

Parameters

U
NumPy array of the data to visualize. If U.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of NumPy arrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
kwargs
See visualize_patch
referenceelements module
class pymor.grids.referenceelements.Line[source]

Bases: pymor.grids.interfaces.ReferenceElementInterface

center()[source]

Coordinates of the barycenter.

mapped_diameter(A)[source]

The diameter of the reference element after transforming it with the matrix A (vectorized).

quadrature(order=None, npoints=None, quadrature_type='default')[source]

Returns tuple (P, W) where P is an array of quadrature points with corresponding weights W.

The quadrature is of order order or has npoints integration points.

quadrature_info()[source]

Returns a tuple of dicts (O, N) where O[quadrature_type] is a list of orders which are implemented for quadrature_type and N[quadrature_type] is a list of the corresponding numbers of integration points.

size(codim)[source]

Number of subentities of codimension codim.

sub_reference_element(codim)[source]

Returns the reference element of the codim-codim subentities.

subentities(codim, subentity_codim)[source]

subentities(c,sc)[i,j] is, with respect to the indexing inside the reference element, the index of the j-th codim-subentity_codim subentity of the i-th codim-codim subentity of the reference element.

subentity_embedding(subentity_codim)[source]

Returns a tuple (A, B) which defines the embedding of the codim-subentity_codim subentities into the reference element.

For subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1) and sub_reference_element(subentity_codim - 1).subentity_embedding(1) choosing always the superentity with smallest index.

unit_outer_normals()[source]

retval[e] is the unit outer-normal vector to the codim-1 subentity with index e.


class pymor.grids.referenceelements.Point[source]

Bases: pymor.grids.interfaces.ReferenceElementInterface

center()[source]

Coordinates of the barycenter.

mapped_diameter(A)[source]

The diameter of the reference element after transforming it with the matrix A (vectorized).

quadrature(order=None, npoints=None, quadrature_type='default')[source]

Returns tuple (P, W) where P is an array of quadrature points with corresponding weights W.

The quadrature is of order order or has npoints integration points.

quadrature_info()[source]

Returns a tuple of dicts (O, N) where O[quadrature_type] is a list of orders which are implemented for quadrature_type and N[quadrature_type] is a list of the corresponding numbers of integration points.

size(codim)[source]

Number of subentities of codimension codim.

sub_reference_element(codim)[source]

Returns the reference element of the codim-codim subentities.

subentities(codim, subentity_codim)[source]

subentities(c,sc)[i,j] is, with respect to the indexing inside the reference element, the index of the j-th codim-subentity_codim subentity of the i-th codim-codim subentity of the reference element.

subentity_embedding(subentity_codim)[source]

Returns a tuple (A, B) which defines the embedding of the codim-subentity_codim subentities into the reference element.

For subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1) and sub_reference_element(subentity_codim - 1).subentity_embedding(1) choosing always the superentity with smallest index.

unit_outer_normals()[source]

retval[e] is the unit outer-normal vector to the codim-1 subentity with index e.


class pymor.grids.referenceelements.Square[source]

Bases: pymor.grids.interfaces.ReferenceElementInterface

center()[source]

Coordinates of the barycenter.

mapped_diameter(A)[source]

The diameter of the reference element after transforming it with the matrix A (vectorized).

quadrature(order=None, npoints=None, quadrature_type='default')[source]

Returns tuple (P, W) where P is an array of quadrature points with corresponding weights W.

The quadrature is of order order or has npoints integration points.

quadrature_info()[source]

Returns a tuple of dicts (O, N) where O[quadrature_type] is a list of orders which are implemented for quadrature_type and N[quadrature_type] is a list of the corresponding numbers of integration points.

size(codim)[source]

Number of subentities of codimension codim.

sub_reference_element(codim)[source]

Returns the reference element of the codim-codim subentities.

subentities(codim, subentity_codim)[source]

subentities(c,sc)[i,j] is, with respect to the indexing inside the reference element, the index of the j-th codim-subentity_codim subentity of the i-th codim-codim subentity of the reference element.

subentity_embedding(subentity_codim)[source]

Returns a tuple (A, B) which defines the embedding of the codim-subentity_codim subentities into the reference element.

For subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1) and sub_reference_element(subentity_codim - 1).subentity_embedding(1) choosing always the superentity with smallest index.

unit_outer_normals()[source]

retval[e] is the unit outer-normal vector to the codim-1 subentity with index e.


class pymor.grids.referenceelements.Triangle[source]

Bases: pymor.grids.interfaces.ReferenceElementInterface

center()[source]

Coordinates of the barycenter.

mapped_diameter(A)[source]

The diameter of the reference element after transforming it with the matrix A (vectorized).

quadrature(order=None, npoints=None, quadrature_type='default')[source]

Returns tuple (P, W) where P is an array of quadrature points with corresponding weights W.

The quadrature is of order order or has npoints integration points.

quadrature_info()[source]

Returns a tuple of dicts (O, N) where O[quadrature_type] is a list of orders which are implemented for quadrature_type and N[quadrature_type] is a list of the corresponding numbers of integration points.

size(codim)[source]

Number of subentities of codimension codim.

sub_reference_element(codim)[source]

Returns the reference element of the codim-codim subentities.

subentities(codim, subentity_codim)[source]

subentities(c,sc)[i,j] is, with respect to the indexing inside the reference element, the index of the j-th codim-subentity_codim subentity of the i-th codim-codim subentity of the reference element.

subentity_embedding(subentity_codim)[source]

Returns a tuple (A, B) which defines the embedding of the codim-subentity_codim subentities into the reference element.

For subentity_codim > 1', the embedding is by default given recursively via `subentity_embedding(subentity_codim - 1) and sub_reference_element(subentity_codim - 1).subentity_embedding(1) choosing always the superentity with smallest index.

unit_outer_normals()[source]

retval[e] is the unit outer-normal vector to the codim-1 subentity with index e.

subgrid module
class pymor.grids.subgrid.SubGrid(grid, entities)[source]

Bases: pymor.grids.interfaces.AffineGridInterface

A subgrid of a Grid.

Given a Grid and a list of codim-0 entities we construct the minimal subgrid of the grid, containing all the given entities.

Parameters

grid
Grid of which a subgrid is to be created.
entities
NumPy array of global indices of the codim-0 entities which are to be contained in the subgrid.
parent_grid

The Grid from which the subgrid was constructed. Subgrid only stores a weakref to the grid, so accessing this property might return None if the original grid has been destroyed.

embeddings(codim)[source]

Returns tuple (A, B) where A[e] and B[e] are the linear part and the translation part of the map from the reference element of e to e.

For codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entity e_0 of e with lowest global index and composing it with the subentity_embedding of e into e_0 determined by the reference element.

indices_from_parent_indices(ind, codim)[source]

Maps a NumPy array of indicies of codim-codim entites of the parent grid to indicies of the subgrid.

Raises

ValueError
Not all provided indices correspond to entities contained in the subgrid.
parent_indices(codim)[source]

retval[e] is the index of the e-th codim-codim entity in the parent grid.

size(codim)[source]

The number of entities of codimension codim.

subentities(codim, subentity_codim)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

The ordering of subentities(0, subentity_codim)[e] has to correspond, w.r.t. the embedding of e, to the local ordering inside the reference element.

For codim > 0, we provide a default implementation by calculating the subentities of e as follows:

  1. Find the codim-1 parent entity e_0 of e with minimal global index
  2. Lookup the local indices of the subentities of e inside e_0 using the reference element.
  3. Map these local indices to global indices using subentities(codim - 1, subentity_codim).

This procedures assures that subentities(codim, subentity_codim)[e] has the right ordering w.r.t. the embedding determined by e_0, which agrees with what is returned by embeddings(codim)

tria module
class pymor.grids.tria.TriaGrid(num_intervals=(2, 2), domain=([0, 0], [1, 1]), identify_left_right=False, identify_bottom_top=False)[source]

Bases: pymor.grids.interfaces.AffineGridWithOrthogonalCentersInterface

Basic implementation of a triangular grid on a rectangular domain.

The global face, edge and vertex indices are given as follows

6---------10----------7---------11----------8
| \                 / | \                 / |
|    22   10    18    |    23   11    19    |
|       \     /       |       \     /       |
3    14   11     6    4    15   12     7    5
|       /     \       |       /     \       |
|    14    2    26    |    15    3    27    |
| /                 \ | /                 \ |
3----------8----------4----------9----------5
| \                 / | \                 / |
|    20    8    16    |    21    9    17    |
|       \     /       |       \     /       |
0    12    9     4    1    13   10     5    2
|       /     \       |       /     \       |
|    12    0    24    |    13    1    25    |
| /                 \ | /                 \ |
0----------6----------1----------7----------2

Parameters

num_intervals
Tuple (n0, n1) determining a grid with n0 x n1 codim-0 entities.
domain
Tuple (ll, ur) where ll defines the lower left and ur the upper right corner of the domain.
identify_left_right
If True, the left and right boundaries are identified, i.e. the left-most codim-0 entities become neighbors of the right-most codim-0 entities.
identify_bottom_top
If True, the bottom and top boundaries are identified, i.e. the bottom-most codim-0 entities become neighbors of the top-most codim-0 entities.
__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

bounding_box()[source]

returns a (2, dim)-shaped array containing lower/upper bounding box coordinates.

embeddings(codim=0)[source]

Returns tuple (A, B) where A[e] and B[e] are the linear part and the translation part of the map from the reference element of e to e.

For codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entity e_0 of e with lowest global index and composing it with the subentity_embedding of e into e_0 determined by the reference element.

orthogonal_centers()[source]

retval[e] is a point inside the codim-0 entity with global index e such that the line segment from retval[e] to retval[e2] is always orthogonal to the codim-1 entity shared by the codim-0 entities with global index e and e2.

(This is mainly useful for gradient approximation in finite volume schemes.)

size(codim=0)[source]

The number of entities of codimension codim.

subentities(codim, subentity_codim)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

The ordering of subentities(0, subentity_codim)[e] has to correspond, w.r.t. the embedding of e, to the local ordering inside the reference element.

For codim > 0, we provide a default implementation by calculating the subentities of e as follows:

  1. Find the codim-1 parent entity e_0 of e with minimal global index
  2. Lookup the local indices of the subentities of e inside e_0 using the reference element.
  3. Map these local indices to global indices using subentities(codim - 1, subentity_codim).

This procedures assures that subentities(codim, subentity_codim)[e] has the right ordering w.r.t. the embedding determined by e_0, which agrees with what is returned by embeddings(codim)

visualize(U, codim=2, **kwargs)[source]

Visualize scalar data associated to the grid as a patch plot.

Parameters

U
NumPy array of the data to visualize. If U.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of NumPy arrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
kwargs
See visualize_patch
unstructured module
class pymor.grids.unstructured.UnstructuredTriangleGrid(vertices, faces)[source]

Bases: pymor.grids.interfaces.AffineGridInterface

A generic unstructured, triangular grid.

Parameters

vertices
A (num_vertices, 2)-shaped NumPy array containing the coordinates of all vertices in the grid. The row numbers in the array will be the global indices of the given vertices (codim 2 entities).
faces
A (num_faces, 3)-shaped NumPy array containing the global indices of the vertices which define a given triangle in the grid. The row numbers in the array will be the global indices of the given triangles (codim 0 entities).
__str__()[source]

Return str(self).

embeddings(codim=0)[source]

Returns tuple (A, B) where A[e] and B[e] are the linear part and the translation part of the map from the reference element of e to e.

For codim > 0, we provide a default implementation by taking the embedding of the codim-1 parent entity e_0 of e with lowest global index and composing it with the subentity_embedding of e into e_0 determined by the reference element.

size(codim=0)[source]

The number of entities of codimension codim.

subentities(codim=0, subentity_codim=None)[source]

retval[e,s] is the global index of the s-th codim-subentity_codim subentity of the codim-codim entity with global index e.

The ordering of subentities(0, subentity_codim)[e] has to correspond, w.r.t. the embedding of e, to the local ordering inside the reference element.

For codim > 0, we provide a default implementation by calculating the subentities of e as follows:

  1. Find the codim-1 parent entity e_0 of e with minimal global index
  2. Lookup the local indices of the subentities of e inside e_0 using the reference element.
  3. Map these local indices to global indices using subentities(codim - 1, subentity_codim).

This procedures assures that subentities(codim, subentity_codim)[e] has the right ordering w.r.t. the embedding determined by e_0, which agrees with what is returned by embeddings(codim)

visualize(U, codim=2, **kwargs)[source]

Visualize scalar data associated to the grid as a patch plot.

Parameters

U
NumPy array of the data to visualize. If U.dim == 2 and len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of NumPy arrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
kwargs
See visualize_patch
pymor.gui package
Submodules
gl module

This module provides a widget for displaying patch plots of scalar data assigned to 2D-grids using OpenGL. This widget is not intended to be used directly. Instead, use visualize_patch or PatchVisualizer.


class pymor.gui.gl.ColorBarWidget(parent, U=None, vmin=None, vmax=None)[source]

Bases: QGLWidget

Methods

ColorBarWidget initializeGL, paintEvent, resizeGL, set

class pymor.gui.gl.GLPatchWidget(parent, grid, vmin=None, vmax=None, bounding_box=([0, 0], [1, 1]), codim=2)[source]

Bases: QGLWidget

Methods

GLPatchWidget initializeGL, paintGL, resizeGL, set, set_coordinates

pymor.gui.gl.colormap_texture(name='viridis')[source]

pymor.gui.gl.compile_shader(source, vertex=True)[source]

Compile a vertex shader from source.


Create a shader program with from compiled shaders.

jupyter module

This module provides plotting support inside the Jupyter notebook.

To use these routines you first have to execute

%matplotlib notebook

inside the given notebook.


pymor.gui.jupyter.visualize_patch(grid, U, bounding_box=([0, 0], [1, 1]), codim=2, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, columns=2)[source]

Visualize scalar data associated to a two-dimensional Grid as a patch plot.

The grid’s ReferenceElement must be the triangle or square. The data can either be attached to the faces or vertices of the grid.

Parameters

grid
The underlying Grid.
U
VectorArray of the data to visualize. If len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of VectorArrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
bounding_box
A bounding box in which the grid is contained.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
title
Title of the plot.
legend
Description of the data that is plotted. Most useful if U is a tuple in which case legend has to be a tuple of strings of the same length.
separate_colorbars
If True, use separate colorbars for each subplot.
rescale_colorbars
If True, rescale colorbars to data in each frame.
columns
The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
matplotlib module

This module provides a widgets for displaying plots of scalar data assigned to one- and two-dimensional grids using matplotlib. This widget is not intended to be used directly.


class pymor.gui.matplotlib.Matplotlib1DWidget(parent, grid, count, vmin=None, vmax=None, legend=None, codim=1, separate_plots=False, dpi=100)[source]

Bases: FigureCanvasQTAgg

Methods

Matplotlib1DWidget set

class pymor.gui.matplotlib.MatplotlibPatchAxes(figure, grid, bounding_box=None, vmin=None, vmax=None, codim=2, colorbar=True)[source]

Bases: object

Methods

MatplotlibPatchAxes set

class pymor.gui.matplotlib.MatplotlibPatchWidget(parent, grid, bounding_box=None, vmin=None, vmax=None, codim=2, dpi=100)[source]

Bases: FigureCanvasQTAgg

Methods

MatplotlibPatchWidget set
qt module

This module provides a few methods and classes for visualizing data associated to grids. We use the Qt widget toolkit for the GUI.


class pymor.gui.qt.PlotMainWindow(U, plot, length=1, title=None)[source]

Bases: object

Base class for plot main windows.

Methods

PlotMainWindow rewind, slider_changed, speed_changed, step_backward, step_forward, to_end, toggle_play, update_solution

pymor.gui.qt._launch_qt_app(main_window_factory, block)[source]

Wrapper to display plot in a separate process.


pymor.gui.qt.stop_gui_processes()[source]

pymor.gui.qt.visualize_matplotlib_1d(grid, U, codim=1, title=None, legend=None, separate_plots=False, block=False)[source]

Visualize scalar data associated to a one-dimensional Grid as a plot.

The grid’s ReferenceElement must be the line. The data can either be attached to the subintervals or vertices of the grid.

Parameters

grid
The underlying Grid.
U
VectorArray of the data to visualize. If len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of VectorArrays can be provided, in which case several plots are made into the same axes. The lengths of all arrays have to agree.
codim
The codimension of the entities the data in U is attached to (either 0 or 1).
title
Title of the plot.
legend
Description of the data that is plotted. Most useful if U is a tuple in which case legend has to be a tuple of strings of the same length.
separate_plots
If True, use subplots to visualize multiple VectorArrays.
block
If True, block execution until the plot window is closed.

pymor.gui.qt.visualize_patch(grid, U, bounding_box=([0, 0], [1, 1]), codim=2, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, backend='gl', block=False, columns=2)[source]

Visualize scalar data associated to a two-dimensional Grid as a patch plot.

The grid’s ReferenceElement must be the triangle or square. The data can either be attached to the faces or vertices of the grid.

Parameters

grid
The underlying Grid.
U
VectorArray of the data to visualize. If len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of VectorArrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
bounding_box
A bounding box in which the grid is contained.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
title
Title of the plot.
legend
Description of the data that is plotted. Most useful if U is a tuple in which case legend has to be a tuple of strings of the same length.
separate_colorbars
If True, use separate colorbars for each subplot.
rescale_colorbars
If True, rescale colorbars to data in each frame.
backend
Plot backend to use (‘gl’ or ‘matplotlib’).
block
If True, block execution until the plot window is closed.
columns
The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.

Defaults

backend (see pymor.core.defaults)

visualizers module
class pymor.gui.visualizers.OnedVisualizer(grid, codim=1, block=False)[source]

Bases: pymor.core.interfaces.BasicInterface

Visualize scalar data associated to a one-dimensional Grid as a plot.

The grid’s ReferenceElement must be the line. The data can either be attached to the subintervals or vertices of the grid.

Parameters

grid
The underlying Grid.
codim
The codimension of the entities the data in U is attached to (either 0 or 1).
block
If True, block execution until the plot window is closed.
visualize(U, d, title=None, legend=None, block=None)[source]

Visualize the provided data.

Parameters

U
VectorArray of the data to visualize. If len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of VectorArrays can be provided, in which case several plots are made into the same axes. The lengths of all arrays have to agree.
d
Filled in by pymor.discretizations.DiscretizationBase.visualize (ignored).
title
Title of the plot.
legend
Description of the data that is plotted. Most useful if U is a tuple in which case legend has to be a tuple of strings of the same length.
block
If True, block execution until the plot window is closed. If None, use the default provided during instantiation.

class pymor.gui.visualizers.PatchVisualizer(grid, bounding_box=([0, 0], [1, 1]), codim=2, backend=None, block=False)[source]

Bases: pymor.core.interfaces.BasicInterface

Visualize scalar data associated to a two-dimensional Grid as a patch plot.

The grid’s ReferenceElement must be the triangle or square. The data can either be attached to the faces or vertices of the grid.

Parameters

grid
The underlying Grid.
bounding_box
A bounding box in which the grid is contained.
codim
The codimension of the entities the data in U is attached to (either 0 or 2).
backend
Plot backend to use (‘gl’, ‘matplotlib’, ‘jupyter’).
block
If True, block execution until the plot window is closed.
visualize(U, d, title=None, legend=None, separate_colorbars=False, rescale_colorbars=False, block=None, filename=None, columns=2)[source]

Visualize the provided data.

Parameters

U
VectorArray of the data to visualize. If len(U) > 1, the data is visualized as a time series of plots. Alternatively, a tuple of VectorArrays can be provided, in which case a subplot is created for each entry of the tuple. The lengths of all arrays have to agree.
d
Filled in by pymor.discretizations.DiscretizationBase.visualize (ignored).
title
Title of the plot.
legend
Description of the data that is plotted. Most useful if U is a tuple in which case legend has to be a tuple of strings of the same length.
separate_colorbars
If True, use separate colorbars for each subplot.
rescale_colorbars
If True, rescale colorbars to data in each frame.
block
If True, block execution until the plot window is closed. If None, use the default provided during instantiation.
filename
If specified, write the data to a VTK-file using pymor.tools.vtkio.write_vtk instead of displaying it.
columns
The number of columns in the visualizer GUI in case multiple plots are displayed at the same time.
pymor.operators package
Submodules
basic module
class pymor.operators.basic.OperatorBase[source]

Bases: pymor.operators.interfaces.OperatorInterface

Base class for Operators providing some default implementations.

When implementing a new operator, it is usually advisable to derive from this class.

__add__(other)[source]

Sum of two operators.

__matmul__(other)[source]

Concatenation of two operators.

__mul__(other)[source]

Product of operator by a scalar.

__str__()[source]

Return str(self).

apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

If the operator is a linear operator given by multiplication with a matrix M, then apply2 is given as:

op.apply2(V, U) = V^T*M*U.

In the case of complex numbers, note that apply2 is anti-linear in the first variable by definition of dot.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V), len(U)) containing the 2-form evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

pairwise_apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

Same as OperatorInterface.apply2, except that vectors from V and U are applied in pairs.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V),) == (len(U),) containing the 2-form evaluations.


class pymor.operators.basic.ProjectedOperator(operator, range_basis, source_basis, product=None, solver_options=None)[source]

Bases: pymor.operators.basic.OperatorBase

Generic Operator representing the projection of an Operator to a subspace.

This operator is implemented as the concatenation of the linear combination with source_basis, application of the original operator and projection onto range_basis. As such, this operator can be used to obtain a reduced basis projection of any given Operator. However, no offline/online decomposition is performed, so this operator is mainly useful for testing before implementing offline/online decomposition for a specific application.

This operator is instantiated in pymor.algorithms.projection.project as a default implementation for parametric or nonlinear operators.

Parameters

operator
The Operator to project.
range_basis
See pymor.algorithms.projection.project.
source_basis
See pymor.algorithms.projection.project.
product
See pymor.algorithms.projection.project.
solver_options
The solver_options for the projected operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

block module
class pymor.operators.block.BlockColumnOperator(blocks, source_id='STATE', range_id='STATE')[source]

Bases: pymor.operators.block.BlockOperatorBase

A column vector of arbitrary Operators.

adjoint_type

alias of BlockRowOperator


class pymor.operators.block.BlockDiagonalOperator(blocks, source_id='STATE', range_id='STATE')[source]

Bases: pymor.operators.block.BlockOperator

Block diagonal Operator of arbitrary Operators.

This is a specialization of BlockOperator for the block diagonal case.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.


class pymor.operators.block.BlockEmbeddingOperator(block_space, component, range_id='STATE')[source]

Bases: pymor.operators.block.BlockColumnOperator


class pymor.operators.block.BlockOperator(blocks, source_id='STATE', range_id='STATE')[source]

Bases: pymor.operators.block.BlockOperatorBase

A matrix of arbitrary Operators.

This operator can be applied to a compatible BlockVectorArrays.

Parameters

blocks
Two-dimensional array-like where each entry is an Operator or None.
adjoint_type

alias of BlockOperator


class pymor.operators.block.BlockOperatorBase(blocks, source_id='STATE', range_id='STATE')[source]

Bases: pymor.operators.basic.OperatorBase

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.


class pymor.operators.block.BlockProjectionOperator(block_space, component, source_id='STATE')[source]

Bases: pymor.operators.block.BlockRowOperator


class pymor.operators.block.BlockRowOperator(blocks, source_id='STATE', range_id='STATE')[source]

Bases: pymor.operators.block.BlockOperatorBase

A row vector of arbitrary Operators.

adjoint_type

alias of BlockColumnOperator


class pymor.operators.block.SecondOrderSystemOperator(E, K)[source]

Bases: pymor.operators.block.BlockOperator

BlockOperator appearing in SecondOrderSystem.to_lti().

This represents a block operator

\mathcal{A} =
\begin{bmatrix}
    0 & I \\
    -K & -E
\end{bmatrix},

which satisfies

\mathcal{A}^H
&=
\begin{bmatrix}
    0 & -K^H \\
    I & -E^H
\end{bmatrix}, \\
\mathcal{A}^{-1}
&=
\begin{bmatrix}
    -K^{-1} E & -K^{-1} \\
    I & 0
\end{bmatrix}, \\
\mathcal{A}^{-H}
&=
\begin{bmatrix}
    -E^H K^{-H} & I \\
    -K^{-H} & 0
\end{bmatrix}.

Parameters

E
Operator.
K
Operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.


class pymor.operators.block.ShiftedSecondOrderSystemOperator(M, E, K, a, b)[source]

Bases: pymor.operators.block.BlockOperator

BlockOperator appearing in second-order systems.

This represents a block operator

a \mathcal{E} + b \mathcal{A} =
\begin{bmatrix}
    a I & b I \\
    -b K & a M - b E
\end{bmatrix},

which satisfies

(a \mathcal{E} + b \mathcal{A})^H
&=
\begin{bmatrix}
    \overline{a} I & -\overline{b} K^H \\
    \overline{b} I & \overline{a} M^H - \overline{b} E^H
\end{bmatrix}, \\
(a \mathcal{E} + b \mathcal{A})^{-1}
&=
\begin{bmatrix}
    (a^2 M - a b E + b^2 K)^{-1} (a M - b E)
    & -b (a^2 M - a b E + b^2 K)^{-1} \\
    b (a^2 M - a b E + b^2 K)^{-1} K
    & a (a^2 M - a b E + b^2 K)^{-1}
\end{bmatrix}, \\
(a \mathcal{E} + b \mathcal{A})^{-H}
&=
\begin{bmatrix}
    (a M - b E)^H (a^2 M - a b E + b^2 K)^{-H}
    & \overline{b} K^H (a^2 M - a b E + b^2 K)^{-H} \\
    -\overline{b} (a^2 M - a b E + b^2 K)^{-H}
    & \overline{a} (a^2 M - a b E + b^2 K)^{-H}
\end{bmatrix}.

Parameters

M
Operator.
E
Operator.
K
Operator.
a, b
Complex numbers.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

cg module

This module provides some operators for continuous finite element discretizations.


class pymor.operators.cg.AdvectionOperatorP1(grid, boundary_info, advection_function=None, advection_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Linear advection Operator for linear finite elements.

The operator is of the form

(Lu)(x) = c ∇ ⋅ [ v(x) u(x) ]

The function v is vector-valued.

Parameters

grid
The Grid for which to assemble the operator.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
advection_function
The Function v(x) with shape_range = (grid.dim, ). If None, constant one is assumed.
advection_constant
The constant c. If None, c is set to one.
dirichlet_clear_columns
If True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero.
dirichlet_clear_diag
If True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one.
solver_options
The solver_options for the operator.
name
Name of the operator.

class pymor.operators.cg.AdvectionOperatorQ1(grid, boundary_info, advection_function=None, advection_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Linear advection Operator for bilinear finite elements.

The operator is of the form

(Lu)(x) = c ∇ ⋅ [ v(x) u(x) ]

The function v has to be vector-valued.

Parameters

grid
The Grid for which to assemble the operator.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
advection_function
The Function v(x) with shape_range = (grid.dim, ). If None, constant one is assumed.
advection_constant
The constant c. If None, c is set to one.
dirichlet_clear_columns
If True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero.
dirichlet_clear_diag
If True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one.
solver_options
The solver_options for the operator.
name
Name of the operator.

class pymor.operators.cg.BoundaryDirichletFunctional(grid, dirichlet_data, boundary_info, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Linear finite element functional for enforcing Dirichlet boundary values.

Parameters

grid
Grid for which to assemble the functional.
dirichlet_data
Function providing the Dirichlet boundary values.
boundary_info
BoundaryInfo determining the Dirichlet boundaries.
name
The name of the functional.

class pymor.operators.cg.BoundaryL2ProductFunctionalP1(grid, function, boundary_type=None, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Linear finite element functional representing the inner product with an L2-Function on the boundary.

Parameters

grid
Grid for which to assemble the functional.
function
The Function with which to take the inner product.
boundary_type
The type of domain boundary (e.g. ‘neumann’) on which to assemble the functional. If None the functional is assembled over the whole boundary.
dirichlet_clear_dofs
If True, set dirichlet boundary DOFs to zero.
boundary_info
If boundary_type is specified or dirichlet_clear_dofs is True, the BoundaryInfo determining which boundary entity belongs to which physical boundary.
order
Order of the Gauss quadrature to use for numerical integration.
name
The name of the functional.

class pymor.operators.cg.BoundaryL2ProductFunctionalQ1(grid, function, boundary_type=None, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Bilinear finite element functional representing the inner product with an L2-Function on the boundary.

Parameters

grid
Grid for which to assemble the functional.
function
The Function with which to take the inner product.
boundary_type
The type of domain boundary (e.g. ‘neumann’) on which to assemble the functional. If None the functional is assembled over the whole boundary.
dirichlet_clear_dofs
If True, set dirichlet boundary DOFs to zero.
boundary_info
If boundary_type is specified or dirichlet_clear_dofs is True, the BoundaryInfo determining which boundary entity belongs to which physical boundary.
order
Order of the Gauss quadrature to use for numerical integration.
name
The name of the functional.

pymor.operators.cg.CGVectorSpace(grid, id_='STATE')[source]

class pymor.operators.cg.DiffusionOperatorP1(grid, boundary_info, diffusion_function=None, diffusion_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Diffusion Operator for linear finite elements.

The operator is of the form

(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]

The function d can be scalar- or matrix-valued.

Parameters

grid
The Grid for which to assemble the operator.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
diffusion_function
The Function d(x) with shape_range == () or shape_range = (grid.dim, grid.dim). If None, constant one is assumed.
diffusion_constant
The constant c. If None, c is set to one.
dirichlet_clear_columns
If True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero.
dirichlet_clear_diag
If True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one.
solver_options
The solver_options for the operator.
name
Name of the operator.

class pymor.operators.cg.DiffusionOperatorQ1(grid, boundary_info, diffusion_function=None, diffusion_constant=None, dirichlet_clear_columns=False, dirichlet_clear_diag=False, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Diffusion Operator for bilinear finite elements.

The operator is of the form

(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]

The function d can be scalar- or matrix-valued.

Parameters

grid
The Grid for which to assemble the operator.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
diffusion_function
The Function d(x) with shape_range == () or shape_range = (grid.dim, grid.dim). If None, constant one is assumed.
diffusion_constant
The constant c. If None, c is set to one.
dirichlet_clear_columns
If True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero to obtain a symmetric system matrix. Otherwise, only the rows will be set to zero.
dirichlet_clear_diag
If True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise they are set to one.
solver_options
The solver_options for the operator.
name
Name of the operator.

class pymor.operators.cg.InterpolationOperator(grid, function)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Vector-like Lagrange interpolation Operator for continuous finite element spaces.

Parameters

grid
The Grid on which to interpolate.
function
The Function to interpolate.

class pymor.operators.cg.L2ProductFunctionalP1(grid, function, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Linear finite element functional representing the inner product with an L2-Function.

Parameters

grid
Grid for which to assemble the functional.
function
The Function with which to take the inner product.
dirichlet_clear_dofs
If True, set dirichlet boundary DOFs to zero.
boundary_info
BoundaryInfo determining the Dirichlet boundaries in case dirichlet_clear_dofs is set to True.
order
Order of the Gauss quadrature to use for numerical integration.
name
The name of the functional.

class pymor.operators.cg.L2ProductFunctionalQ1(grid, function, dirichlet_clear_dofs=False, boundary_info=None, order=2, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Bilinear finite element functional representing the inner product with an L2-Function.

Parameters

grid
Grid for which to assemble the functional.
function
The Function with which to take the inner product.
dirichlet_clear_dofs
If True, set dirichlet boundary DOFs to zero.
boundary_info
BoundaryInfo determining the Dirichlet boundaries in case dirichlet_clear_dofs is set to True.
order
Order of the Gauss quadrature to use for numerical integration.
name
The name of the functional.

class pymor.operators.cg.L2ProductP1(grid, boundary_info, dirichlet_clear_rows=True, dirichlet_clear_columns=False, dirichlet_clear_diag=False, coefficient_function=None, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Operator representing the L2-product between linear finite element functions.

Parameters

grid
The Grid for which to assemble the product.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
dirichlet_clear_rows
If True, set the rows of the system matrix corresponding to Dirichlet boundary DOFs to zero.
dirichlet_clear_columns
If True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero.
dirichlet_clear_diag
If True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise, if either dirichlet_clear_rows or dirichlet_clear_columns is True, the diagonal entries are set to one.
coefficient_function
Coefficient Function for product with shape_range == (). If None, constant one is assumed.
solver_options
The solver_options for the operator.
name
The name of the product.

class pymor.operators.cg.L2ProductQ1(grid, boundary_info, dirichlet_clear_rows=True, dirichlet_clear_columns=False, dirichlet_clear_diag=False, coefficient_function=None, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Operator representing the L2-product between bilinear finite element functions.

Parameters

grid
The Grid for which to assemble the product.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
dirichlet_clear_rows
If True, set the rows of the system matrix corresponding to Dirichlet boundary DOFs to zero.
dirichlet_clear_columns
If True, set columns of the system matrix corresponding to Dirichlet boundary DOFs to zero.
dirichlet_clear_diag
If True, also set diagonal entries corresponding to Dirichlet boundary DOFs to zero. Otherwise, if either dirichlet_clear_rows or dirichlet_clear_columns is True, the diagonal entries are set to one.
coefficient_function
Coefficient Function for product with shape_range == (). If None, constant one is assumed.
solver_options
The solver_options for the operator.
name
The name of the product.

class pymor.operators.cg.RobinBoundaryOperator(grid, boundary_info, robin_data=None, order=2, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Robin boundary Operator for linear finite elements.

The operator represents the contribution of Robin boundary conditions to the stiffness matrix, where the boundary condition is supposed to be given in the form

-[ d(x) ∇u(x) ] ⋅ n(x) = c(x) (u(x) - g(x))

d and n are the diffusion function (see DiffusionOperatorP1) and the unit outer normal in x, while c is the (scalar) Robin parameter function and g is the (also scalar) Robin boundary value function.

Parameters

grid
The Grid over which to assemble the operator.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
robin_data
Tuple providing two Functions that represent the Robin parameter and boundary value function. If None, the resulting operator is zero.
solver_options
The solver_options for the operator.
name
Name of the operator.
constructions module

Module containing some constructions to obtain new operators from old ones.


class pymor.operators.constructions.AdjointOperator(operator, source_product=None, range_product=None, name=None, with_apply_inverse=True, solver_options=None)[source]

Bases: pymor.operators.basic.OperatorBase

Represents the adjoint of a given linear Operator.

For a linear Operator op the adjoint op^* of op is given by:

(op^*(v), u)_s = (v, op(u))_r,

where ( , )_s and ( , )_r denote the inner products on the source and range space of op. If two products are given by P_s and P_r, then:

op^*(v) = P_s^(-1) o op.H o P_r,

Thus, if ( , )_s and ( , )_r are the Euclidean inner products, op^*v is simply given by application of the :attr:adjoint <pymor.operators.interface.OperatorInterface.H>` Operator.

Parameters

operator
The Operator of which the adjoint is formed.
source_product
If not None, inner product Operator for the source VectorSpace w.r.t. which to take the adjoint.
range_product
If not None, inner product Operator for the range VectorSpace w.r.t. which to take the adjoint.
name
If not None, name of the operator.
with_apply_inverse
If True, provide own apply_inverse and apply_inverse_adjoint implementations by calling these methods on the given operator. (Is set to False in the default implementation of and apply_inverse_adjoint.)
solver_options
When with_apply_inverse is False, the solver_options to use for the apply_inverse default implementation.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.

class pymor.operators.constructions.AffineOperator(operator, name=None)[source]

Bases: pymor.operators.constructions.ProxyOperator

Decompose an affine Operator into affine_shift and linear_part.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.


class pymor.operators.constructions.ComponentProjection(components, source, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Operator representing the projection of a VectorArray onto some of its components.

Parameters

components
List or 1D NumPy array of the indices of the vector components that are to be extracted by the operator.
source
Source VectorSpace of the operator.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

class pymor.operators.constructions.Concatenation(operators, solver_options=None, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Operator representing the concatenation of two Operators.

Parameters

operators
Tuple of Operators to concatenate. operators[-1] is the first applied operator, operators[0] is the last applied operator.
solver_options
The solver_options for the operator.
name
Name of the operator.
__matmul__(other)[source]

Concatenation of two operators.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

class pymor.operators.constructions.ConstantOperator(value, source, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

A constant Operator always returning the same vector.

Parameters

value
A VectorArray of length 1 containing the vector which is returned by the operator.
source
Source VectorSpace of the operator.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

class pymor.operators.constructions.FixedParameterOperator(operator, mu=None, name=None)[source]

Bases: pymor.operators.constructions.ProxyOperator

Makes an Operator Parameter-independent by setting a fixed Parameter.

Parameters

operator
The Operator to wrap.
mu
The fixed Parameter that will be fed to the apply method (and related methods) of operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.


class pymor.operators.constructions.IdentityOperator(space, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

The identity Operator.

In other words:

op.apply(U) == U

Parameters

space
The VectorSpace the operator acts on.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

class pymor.operators.constructions.InducedNorm(product, raise_negative, tol, name)[source]

Bases: pymor.core.interfaces.ImmutableInterface, pymor.parameters.base.Parametric

Instantiated by induced_norm. Do not use directly.

__call__(U, mu=None)[source]

Call self as a function.


class pymor.operators.constructions.InverseAdjointOperator(operator, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Represents the inverse adjoint of a given Operator.

Parameters

operator
The Operator of which the inverse adjoint is formed.
name
If not None, name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.

class pymor.operators.constructions.InverseOperator(operator, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Represents the inverse of a given Operator.

Parameters

operator
The Operator of which the inverse is formed.
name
If not None, name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.

class pymor.operators.constructions.LincombOperator(operators, coefficients, solver_options=None, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Linear combination of arbitrary Operators.

This Operator represents a (possibly Parameter dependent) linear combination of a given list of Operators.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
A list of linear coefficients. A linear coefficient can either be a fixed number or a ParameterFunctional.
solver_options
The solver_options for the operator.
name
Name of the operator.
__add__(other)[source]

Sum of two operators.

__mul__(other)[source]

Product of operator by a scalar.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

If the operator is a linear operator given by multiplication with a matrix M, then apply2 is given as:

op.apply2(V, U) = V^T*M*U.

In the case of complex numbers, note that apply2 is anti-linear in the first variable by definition of dot.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V), len(U)) containing the 2-form evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

evaluate_coefficients(mu)[source]

Compute the linear coefficients for a given Parameter.

Parameters

mu
Parameter for which to compute the linear coefficients.

Returns

List of linear coefficients.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

pairwise_apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

Same as OperatorInterface.apply2, except that vectors from V and U are applied in pairs.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V),) == (len(U),) containing the 2-form evaluations.


class pymor.operators.constructions.LinearOperator(operator, name=None)[source]

Bases: pymor.operators.constructions.ProxyOperator

Mark the wrapped Operator to be linear.


class pymor.operators.constructions.ProxyOperator(operator, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Forwards all interface calls to given Operator.

Mainly useful as base class for other Operator implementations.

Parameters

operator
The Operator to wrap.
name
Name of the wrapping operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

class pymor.operators.constructions.SelectionOperator(operators, parameter_functional, boundaries, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

An Operator selected from a list of Operators.

operators[i] is used if parameter_functional(mu) is less or equal than boundaries[i] and greater than boundaries[i-1]:

-infty ------- boundaries[i] ---------- boundaries[i+1] ------- infty
                    |                        |
--- operators[i] ---|---- operators[i+1] ----|---- operators[i+2]
                    |                        |

Parameters

operators
List of Operators from which one Operator is selected based on the given Parameter.
parameter_functional
The ParameterFunctional used for the selection of one Operator.
boundaries
The interval boundaries as defined above.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.


class pymor.operators.constructions.VectorArrayOperator(array, adjoint=False, space_id=None, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Wraps a VectorArray as an Operator.

If adjoint is False, the operator maps from NumpyVectorSpace(len(array)) to array.space by forming linear combinations of the vectors in the array with given coefficient arrays.

If adjoint == True, the operator maps from array.space to NumpyVectorSpace(len(array)) by forming the inner products of the argument with the vectors in the given array.

Parameters

array
The VectorArray which is to be treated as an operator.
adjoint
See description above.
space_id
Id of the source (range) VectorSpace in case adjoint is False (True).
name
The name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

class pymor.operators.constructions.VectorFunctional(vector, product=None, name=None)[source]

Bases: pymor.operators.constructions.VectorArrayOperator

Wrap a vector as a linear Functional.

Given a vector v of dimension d, this class represents the functional

f: R^d ----> R^1
    u  |---> (u, v)

where ( , ) denotes the inner product given by product.

In particular, if product is None

VectorFunctional(vector).as_source_array() == vector.

If product is not none, we obtain

VectorFunctional(vector).as_source_array() == product.apply(vector).

Parameters

vector
VectorArray of length 1 containing the vector v.
product
Operator representing the scalar product to use.
name
Name of the operator.

class pymor.operators.constructions.VectorOperator(vector, name=None)[source]

Bases: pymor.operators.constructions.VectorArrayOperator

Wrap a vector as a vector-like Operator.

Given a vector v of dimension d, this class represents the operator

op: R^1 ----> R^d
     x  |---> x⋅v

In particular:

VectorOperator(vector).as_range_array() == vector

Parameters

vector
VectorArray of length 1 containing the vector v.
name
Name of the operator.

class pymor.operators.constructions.ZeroOperator(range, source, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

The Operator which maps every vector to zero.

Parameters

range
Range VectorSpace of the operator.
source
Source VectorSpace of the operator.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

pymor.operators.constructions.induced_norm(product, raise_negative=True, tol=1e-10, name=None)[source]

Obtain induced norm of an inner product.

The norm of the vectors in a VectorArray U is calculated by calling

product.pairwise_apply2(U, U, mu=mu).

In addition, negative norm squares of absolute value smaller than tol are clipped to 0. If raise_negative is True, a ValueError exception is raised if there are negative norm squares of absolute value larger than tol.

Parameters

product
The inner product Operator for which the norm is to be calculated.
raise_negative
If True, raise an exception if calculated norm is negative.
tol
See above.
name
optional, if None product’s name is used

Returns

norm
A function norm(U, mu=None) taking a VectorArray U as input together with the Parameter mu which is passed to the product.

Defaults

raise_negative, tol (see pymor.core.defaults)

ei module
class pymor.operators.ei.EmpiricalInterpolatedOperator(operator, interpolation_dofs, collateral_basis, triangular, solver_options=None, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Interpolate an Operator using Empirical Operator Interpolation.

Let L be an Operator, 0 <= c_1, ..., c_M < L.range.dim indices of interpolation DOFs and let b_1, ..., b_M in R^(L.range.dim) be collateral basis vectors. If moreover ψ_j(U) denotes the j-th component of U, the empirical interpolation L_EI of L w.r.t. the given data is given by

|                M
|   L_EI(U, μ) = ∑ b_i⋅λ_i     such that
|               i=1
|
|   ψ_(c_i)(L_EI(U, μ)) = ψ_(c_i)(L(U, μ))   for i=0,...,M

Since the original operator only has to be evaluated at the given interpolation DOFs, EmpiricalInterpolatedOperator calls restricted to obtain a restricted version of the operator which is used to quickly obtain the required evaluations. If the restricted method, is not implemented, the full operator will be evaluated (which will lead to the same result, but without any speedup).

The interpolation DOFs and the collateral basis can be generated using the algorithms provided in the pymor.algorithms.ei module.

Parameters

operator
The Operator to interpolate.
interpolation_dofs
List or 1D NumPy array of the interpolation DOFs c_1, ..., c_M.
collateral_basis
VectorArray containing the collateral basis b_1, ..., b_M.
triangular
If True, assume that ψ_(c_i)(b_j) = 0 for i < j, which means that the interpolation matrix is triangular.
solver_options
The solver_options for the operator.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.


class pymor.operators.ei.ProjectedEmpiciralInterpolatedOperator(restricted_operator, interpolation_matrix, source_basis_dofs, projected_collateral_basis, triangular, source_id, solver_options=None, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

A projected EmpiricalInterpolatedOperator.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

fv module

This module provides some operators for finite volume discretizations.


class pymor.operators.fv.DiffusionOperator(grid, boundary_info, diffusion_function=None, diffusion_constant=None, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Finite Volume Diffusion Operator.

The operator is of the form

(Lu)(x) = c ∇ ⋅ [ d(x) ∇ u(x) ]

Parameters

grid
The Grid over which to assemble the operator.
boundary_info
BoundaryInfo for the treatment of Dirichlet boundary conditions.
diffusion_function
The scalar-valued Function d(x). If None, constant one is assumed.
diffusion_constant
The constant c. If None, c is set to one.
solver_options
The solver_options for the operator.
name
Name of the operator.

class pymor.operators.fv.EngquistOsherFlux(flux, flux_derivative, gausspoints=5, intervals=1)[source]

Bases: pymor.operators.fv.NumericalConvectiveFluxInterface

Engquist-Osher numerical flux.

If f is the analytical flux, and f' its derivative, the Engquist-Osher flux is given by:

F(U_in, U_out, normal, vol) = vol * [c^+(U_in, normal)  +  c^-(U_out, normal)]

                                   U_in
c^+(U_in, normal)  = f(0)⋅normal +  ∫   max(f'(s)⋅normal, 0) ds
                                   s=0

                                  U_out
c^-(U_out, normal) =                ∫   min(f'(s)⋅normal, 0) ds
                                   s=0

Parameters

flux
Function defining the analytical flux f.
flux_derivative
Function defining the analytical flux derivative f'.
gausspoints
Number of Gauss quadrature points to be used for integration.
intervals
Number of subintervals to be used for integration.

pymor.operators.fv.FVVectorSpace(grid, id_='STATE')[source]

class pymor.operators.fv.L2Product(grid, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Operator representing the L2-product between finite volume functions.

Parameters

grid
The Grid for which to assemble the product.
solver_options
The solver_options for the operator.
name
The name of the product.

class pymor.operators.fv.L2ProductFunctional(grid, function=None, boundary_info=None, dirichlet_data=None, diffusion_function=None, diffusion_constant=None, neumann_data=None, order=1, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Finite volume functional representing the inner product with an L2-Function.

Additionally, boundary conditions can be enforced by providing dirichlet_data and neumann_data functions.

Parameters

grid
Grid for which to assemble the functional.
function
The Function with which to take the inner product or None.
boundary_info
BoundaryInfo determining the Dirichlet and Neumann boundaries or None. If None, no boundary treatment is performed.
dirichlet_data
Function providing the Dirichlet boundary values. If None, constant-zero boundary is assumed.
diffusion_function
See DiffusionOperator. Has to be specified in case dirichlet_data is given.
diffusion_constant
See DiffusionOperator. Has to be specified in case dirichlet_data is given.
neumann_data
Function providing the Neumann boundary values. If None, constant-zero is assumed.
order
Order of the Gauss quadrature to use for numerical integration.
name
The name of the functional.

class pymor.operators.fv.LaxFriedrichsFlux(flux, lxf_lambda=1.0)[source]

Bases: pymor.operators.fv.NumericalConvectiveFluxInterface

Lax-Friedrichs numerical flux.

If f is the analytical flux, the Lax-Friedrichs flux F is given by:

F(U_in, U_out, normal, vol) = vol * [normal⋅(f(U_in) + f(U_out))/2 + (U_in - U_out)/(2*λ)]

Parameters

flux
Function defining the analytical flux f.
lxf_lambda
The stabilization parameter λ.

class pymor.operators.fv.LinearAdvectionLaxFriedrichs(grid, boundary_info, velocity_field, lxf_lambda=1.0, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Linear advection finite Volume Operator using Lax-Friedrichs flux.

The operator is of the form

L(u, mu)(x) = ∇ ⋅ (v(x, mu)⋅u(x))

See LaxFriedrichsFlux for the definition of the Lax-Friedrichs flux.

Parameters

grid
Grid over which to assemble the operator.
boundary_info
BoundaryInfo determining the Dirichlet and Neumann boundaries.
velocity_field
Function defining the velocity field v.
lxf_lambda
The stabilization parameter λ.
solver_options
The solver_options for the operator.
name
The name of the operator.

class pymor.operators.fv.NonlinearAdvectionOperator(grid, boundary_info, numerical_flux, dirichlet_data=None, solver_options=None, space_id='STATE', name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Nonlinear finite volume advection Operator.

The operator is of the form

L(u, mu)(x) = ∇ ⋅ f(u(x), mu)

Parameters

grid
Grid for which to evaluate the operator.
boundary_info
BoundaryInfo determining the Dirichlet and Neumann boundaries.
numerical_flux
The NumericalConvectiveFlux to use.
dirichlet_data
Function providing the Dirichlet boundary values. If None, constant-zero boundary is assumed.
solver_options
The solver_options for the operator.
name
The name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.
with_(**kwargs)[source]

Returns a copy with changed attributes.

The default implementation is to create a new class instance with the given keyword arguments as arguments for __init__. Missing arguments are obtained form instance attributes with the same name.

Parameters

**kwargs
Names of attributes to change with their new values. Each attribute name has to be contained in with_arguments.

Returns

Copy of self with changed attributes.


class pymor.operators.fv.NonlinearReactionOperator(grid, reaction_function, reaction_function_derivative=None, space_id='STATE', name=None)[source]

Bases: pymor.operators.basic.OperatorBase

apply(U, ind=None, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.


class pymor.operators.fv.NumericalConvectiveFluxInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface, pymor.parameters.base.Parametric

Interface for numerical convective fluxes for finite volume schemes.

Numerical fluxes defined by this interfaces are functions of the form F(U_inner, U_outer, unit_outer_normal, edge_volume, mu).

The flux evaluation is vectorized and happens in two stages:
  1. evaluate_stage1 receives a NumPy array U of all values which appear as U_inner or U_outer for all edges the flux shall be evaluated at and returns a tuple of NumPy arrays each of the same length as U.

  2. evaluate_stage2 receives the reordered stage1_data for each edge as well as the unit outer normal and the volume of the edges.

    stage1_data is given as follows: If R_l is l-th entry of the tuple returned by evaluate_stage1, the l-th entry D_l of of the stage1_data tuple has the shape (num_edges, 2) + R_l.shape[1:]. If for edge k the values U_inner and U_outer are the i-th and j-th value in the U array provided to evaluate_stage1, we have

    D_l[k, 0] == R_l[i],    D_l[k, 1] == R_l[j].
    

    evaluate_stage2 returns a NumPy array of the flux evaluations for each edge.


class pymor.operators.fv.ReactionOperator(grid, reaction_coefficient, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Finite Volume reaction Operator.

The operator is of the form

L(u, mu)(x) = c(x, mu)⋅u(x)

Parameters

grid
The Grid for which to assemble the operator.
reaction_coefficient
The function ‘c’
solver_options
The solver_options for the operator.
name
The name of the operator.

class pymor.operators.fv.SimplifiedEngquistOsherFlux(flux, flux_derivative)[source]

Bases: pymor.operators.fv.NumericalConvectiveFluxInterface

Engquist-Osher numerical flux. Simplified Implementation for special case.

For the definition of the Engquist-Osher flux see EngquistOsherFlux. This class provides a faster and more accurate implementation for the special case that f(0) == 0 and the derivative of f only changes sign at 0.

Parameters

flux
Function defining the analytical flux f.
flux_derivative
Function defining the analytical flux derivative f'.

pymor.operators.fv.jacobian_options(delta=1e-07)[source]

pymor.operators.fv.nonlinear_advection_engquist_osher_operator(grid, boundary_info, flux, flux_derivative, gausspoints=5, intervals=1, dirichlet_data=None, solver_options=None, name=None)[source]

Instantiate a NonlinearAdvectionOperator using EngquistOsherFlux.


pymor.operators.fv.nonlinear_advection_lax_friedrichs_operator(grid, boundary_info, flux, lxf_lambda=1.0, dirichlet_data=None, solver_options=None, name=None)[source]

Instantiate a NonlinearAdvectionOperator using LaxFriedrichsFlux.


pymor.operators.fv.nonlinear_advection_simplified_engquist_osher_operator(grid, boundary_info, flux, flux_derivative, dirichlet_data=None, solver_options=None, name=None)[source]

Instantiate a NonlinearAdvectionOperator using SimplifiedEngquistOsherFlux.

interfaces module
class pymor.operators.interfaces.OperatorInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface, pymor.parameters.base.Parametric

Interface for Parameter dependent discrete operators.

An operator in pyMOR is simply a mapping which for any given Parameter maps vectors from its source VectorSpace to vectors in its range VectorSpace.

Note that there is no special distinction between functionals and operators in pyMOR. A functional is simply an operator with NumpyVectorSpace (1) as its range VectorSpace.

solver_options

If not None, a dict which can contain the following keys:

‘inverse’:solver options used for apply_inverse
‘inverse_adjoint’:solver options used for apply_inverse_adjoint
‘jacobian’:solver options for the operators returned by jacobian (has no effect for linear operators)

If solver_options is None or a dict entry is missing or None, default options are used. The interpretation of the given solver options is up to the operator at hand. In general, values in solver_options should either be strings (indicating a solver type) or dicts of options, usually with an entry 'type' which specifies the solver type to use and further items which configure this solver.

linear

True if the operator is linear.

source

The source VectorSpace.

range

The range VectorSpace.

H

The adjoint operator, i.e.

self.H.apply(V, mu) == self.apply_adjoint(V, mu)

for all V, mu.

__add__(other)[source]

Sum of two operators.

__matmul__(other)[source]

Concatenation of two operators.

__mul__(other)[source]

Product of operator by a scalar.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

If the operator is a linear operator given by multiplication with a matrix M, then apply2 is given as:

op.apply2(V, U) = V^T*M*U.

In the case of complex numbers, note that apply2 is anti-linear in the first variable by definition of dot.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V), len(U)) containing the 2-form evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_vector(mu=None, *, space=None)[source]

Return a vector representation of a linear functional or vector operator.

Depending on the operator’s source and range, this method is equivalent to calling as_range_array or as_source_array respectively. The resulting VectorArray is required to have length 1.

Note that in case both source and range are one-dimensional NumpyVectorSpaces but with different ids, it is impossible to determine which space to choose. In this case, the desired space has to be specified via the space parameter.

Parameters

mu
The Parameter for which to return the vector representation.
space
See above.

Returns

V
VectorArray of length 1 containing the vector representation.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

pairwise_apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

Same as OperatorInterface.apply2, except that vectors from V and U are applied in pairs.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V),) == (len(U),) containing the 2-form evaluations.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.
mpi module
class pymor.operators.mpi.MPIOperator(obj_id, with_apply2=False, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]

Bases: pymor.operators.basic.OperatorBase

MPI distributed Operator.

Given a single-rank implementation of an Operator, this wrapper class uses the event loop from pymor.tools.mpi to allow an MPI distributed usage of the Operator.

Instances of MPIOperator can be used on rank 0 like any other (non-distributed) Operator.

Note, however, that the underlying Operator implementation needs to be MPI aware. For instance, the operator’s apply method has to perform the necessary MPI communication to obtain all DOFs hosted on other MPI ranks which are required for the local operator evaluation.

Instead of instantiating MPIOperator directly, it is usually preferable to use mpi_wrap_operator instead.

Parameters

obj_id
ObjectId of the local Operators on each rank.
with_apply2
Set to True if the operator implementation has its own MPI aware implementation of apply2 and pairwise_apply2. Otherwise, the default implementations using apply and dot will be used.
pickle_local_spaces
If pickle_local_spaces is False, a unique identifier is computed for each local source/range VectorSpace, which is then transferred to rank 0 instead of the true VectorSpace. This allows the useage of MPIVectorArray even when the local VectorSpaces are not picklable.
space_type
This class will be used to wrap the local VectorArrays returned by the local operators into an MPI distributed VectorArray managed from rank 0. By default, MPIVectorSpace will be used, other options are MPIVectorSpaceAutoComm and MPIVectorSpaceNoComm.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

If the operator is a linear operator given by multiplication with a matrix M, then apply2 is given as:

op.apply2(V, U) = V^T*M*U.

In the case of complex numbers, note that apply2 is anti-linear in the first variable by definition of dot.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V), len(U)) containing the 2-form evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

jacobian(U, mu=None)[source]

Return the operator’s Jacobian as a new Operator.

Parameters

U
Length 1 VectorArray containing the vector for which to compute the Jacobian.
mu
The Parameter for which to compute the Jacobian.

Returns

Linear Operator representing the Jacobian.

pairwise_apply2(V, U, mu=None)[source]

Treat the operator as a 2-form by computing V.dot(self.apply(U)).

Same as OperatorInterface.apply2, except that vectors from V and U are applied in pairs.

Parameters

V
VectorArray of the left arguments V.
U
VectorArray of the right right arguments U.
mu
The Parameter for which to evaluate the operator.

Returns

A NumPy array with shape (len(V),) == (len(U),) containing the 2-form evaluations.

restricted(dofs)[source]

Restrict the operator range to a given set of degrees of freedom.

This method returns a restricted version restricted_op of the operator along with an array source_dofs such that for any VectorArray U in self.source the following is true:

self.apply(U, mu).dofs(dofs)
    == restricted_op.apply(NumpyVectorArray(U.dofs(source_dofs)), mu))

Such an operator is mainly useful for empirical interpolation where the evaluation of the original operator only needs to be known for few selected degrees of freedom. If the operator has a small stencil, only few source_dofs will be needed to evaluate the restricted operator which can make its evaluation very fast compared to evaluating the original operator.

Parameters

dofs
One-dimensional NumPy array of degrees of freedom in the operator range to which to restrict.

Returns

restricted_op
The restricted operator as defined above. The operator will have NumpyVectorSpace (len(source_dofs)) as source and NumpyVectorSpace (len(dofs)) as range.
source_dofs
One-dimensional NumPy array of source degrees of freedom as defined above.

pymor.operators.mpi.mpi_wrap_operator(obj_id, with_apply2=False, pickle_local_spaces=True, space_type=<class 'pymor.vectorarrays.mpi.MPIVectorSpace'>)[source]

Wrap MPI distributed local Operators to a global Operator on rank 0.

Given MPI distributed local Operators referred to by the ObjectId obj_id, return a new Operator which manages these distributed operators from rank 0. This is done by instantiating MPIOperator. Additionally, the structure of the wrapped operators is preserved. E.g. LincombOperators will be wrapped as a LincombOperator of MPIOperators.

Parameters

See : class:MPIOperator.

Returns

The wrapped Operator.

numpy module

This module provides the following NumPy based Operators:


class pymor.operators.numpy.NumpyGenericOperator(mapping, adjoint_mapping=None, dim_source=1, dim_range=1, linear=False, parameter_type=None, source_id=None, range_id=None, solver_options=None, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Wraps an arbitrary Python function between NumPy arrays as an Operator.

Parameters

mapping

The function to wrap. If parameter_type is None, the function is of the form mapping(U) and is expected to be vectorized. In particular:

mapping(U).shape == U.shape[:-1] + (dim_range,).

If parameter_type is not None, the function has to have the signature mapping(U, mu).

adjoint_mapping

The adjoint function to wrap. If parameter_type is None, the function is of the form adjoint_mapping(U) and is expected to be vectorized. In particular:

adjoint_mapping(U).shape == U.shape[:-1] + (dim_source,).

If parameter_type is not None, the function has to have the signature adjoint_mapping(U, mu).

dim_source
Dimension of the operator’s source.
dim_range
Dimension of the operator’s range.
linear
Set to True if the provided mapping and adjoint_mapping are linear.
parameter_type
The ParameterType of the Parameters the mapping accepts.
solver_options
The solver_options for the operator.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.


class pymor.operators.numpy.NumpyMatrixBasedOperator[source]

Bases: pymor.operators.basic.OperatorBase

Base class for operators which assemble into a NumpyMatrixOperator.

sparse

True if the operator assembles into a sparse matrix, False if the operator assembles into a dense matrix, None if unknown.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

export_matrix(filename, matrix_name=None, output_format='matlab', mu=None)[source]

Save the matrix of the operator to a file.

Parameters

filename
Name of output file.
matrix_name
The name, the output matrix is given. (Comment field is used in case of Matrix Market output_format.) If None, the Operator’s name is used.
output_format
Output file format. Either matlab or matrixmarket.
mu
The Parameter to assemble the to be exported matrix for.

class pymor.operators.numpy.NumpyMatrixOperator(matrix, source_id=None, range_id=None, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixBasedOperator

Wraps a 2D NumPy array as an Operator.

Parameters

matrix
The NumPy array which is to be wrapped.
source_id
The id of the operator’s source VectorSpace.
range_id
The id of the operator’s range VectorSpace.
solver_options
The solver_options for the operator.
name
Name of the operator.
apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False, check_finite=True, default_sparse_solver_backend='scipy')[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

check_finite
Test if solution only contains finite values.
default_sparse_solver_backend
Default sparse solver backend to use (scipy, pyamg, generic).

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.

Defaults

check_finite, default_sparse_solver_backend (see pymor.core.defaults)

apply_inverse_adjoint(U, mu=None, least_squares=False)[source]

Apply the inverse adjoint operator.

Parameters

U
VectorArray of vectors to which the inverse adjoint operator is applied.
mu
The Parameter for which to evaluate the inverse adjoint operator.
least_squares

If True, solve the least squares problem:

v = argmin ||op^*(v) - u||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most operator implementations will choose a least squares solver by default which may be undesirable.

Returns

VectorArray of the inverse adjoint operator evaluations.

Raises

InversionError
The operator could not be inverted.
as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble(mu=None)[source]

Assemble the operator for a given parameter.

The result of the method strongly depends on the given operator. For instance, a matrix-based operator will assemble its matrix, a LincombOperator will try to form the linear combination of its operators, whereas an arbitrary operator might simply return a FixedParameterOperator. The only assured property of the assembled operator is that it no longer depends on a Parameter.

Parameters

mu
The Parameter for which to assemble the operator.

Returns

Parameter-independent, assembled Operator.

assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

pymor.parallel package
Submodules
basic module

This module contains a base class for implementing WorkerPoolInterface.


class pymor.parallel.basic.RemoteObject(pool, remote_id, uid=None)[source]

Bases: pymor.parallel.interfaces.RemoteObjectInterface


class pymor.parallel.basic.WorkerPoolBase[source]

Bases: pymor.parallel.basic.WorkerPoolDefaultImplementations, pymor.parallel.interfaces.WorkerPoolInterface

apply(function, *args, **kwargs)[source]

Apply function in parallel on each worker.

This calls function on each worker in parallel, passing args as positional and kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute on each worker.
args
The positional arguments for function.
kwargs
The keyword arguments for function.

Returns

List of return values of the function executions, ordered by worker number (from 0 to len(pool) - 1).

apply_only(function, worker, *args, **kwargs)[source]

Apply function on a single worker.

This calls function on on the worker with number worker, passing args as positional and kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute.
worker
The worker on which to execute the function. (Number between 0 and len(pool) - 1.)
args
The positional arguments for function.
kwargs
The keyword arguments for function.

Returns

Return value of the function execution.

map(function, *args, **kwargs)[source]

Parallel version of the builtin map function.

Each positional argument (after function) must be a sequence of same length n. map calls function in parallel on each of these n positional argument combinations, always passing kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute on each worker.
args
The sequences of positional arguments for function.
kwargs
The keyword arguments for function.

Returns

List of return values of the function executions, ordered by the sequence of positional arguments.

push(obj)[source]

Push a copy of obj to all workers of the pool.

A RemoteObject is returned as a handle to the pushed object. This object can be used as a keyword argument to apply, apply_only, map and will then be transparently mapped to the respective copy of the pushed object on the worker.

Immutable objects will be pushed only once. If the same immutable object is pushed a second time, the returned RemoteObject will refer to the already transferred copy. It is therefore safe to use push to ensure that a given immutable object is available on the worker. No unnecessary copies will be created.

Parameters

obj
The object to push to all workers.

Returns

A RemoteObject referring to the pushed data.


class pymor.parallel.basic.WorkerPoolDefaultImplementations[source]

Bases: object

Methods

WorkerPoolDefaultImplementations scatter_array, scatter_list
default module
pymor.parallel.default.new_parallel_pool(ipython_num_engines=None, ipython_profile=None, allow_mpi=True)[source]

Creates a new default WorkerPool.

If ipython_num_engines or ipython_profile is provided as an argument or set as a default, an IPythonPool WorkerPool will be created using the given parameters via the ipcluster script.

Otherwise, when allow_mpi is True and an MPI parallel run is detected, an MPIPool WorkerPool will be created.

Otherwise, a sequential run is assumed and pymor.parallel.dummy.dummy_pool is returned.

Defaults

ipython_num_engines, ipython_profile, allow_mpi (see pymor.core.defaults)

dummy module
class pymor.parallel.dummy.DummyPool[source]

Bases: pymor.parallel.interfaces.WorkerPoolInterface

__len__()[source]

The number of workers in the pool.

apply(function, *args, **kwargs)[source]

Apply function in parallel on each worker.

This calls function on each worker in parallel, passing args as positional and kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute on each worker.
args
The positional arguments for function.
kwargs
The keyword arguments for function.

Returns

List of return values of the function executions, ordered by worker number (from 0 to len(pool) - 1).

apply_only(function, worker, *args, **kwargs)[source]

Apply function on a single worker.

This calls function on on the worker with number worker, passing args as positional and kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute.
worker
The worker on which to execute the function. (Number between 0 and len(pool) - 1.)
args
The positional arguments for function.
kwargs
The keyword arguments for function.

Returns

Return value of the function execution.

map(function, *args, **kwargs)[source]

Parallel version of the builtin map function.

Each positional argument (after function) must be a sequence of same length n. map calls function in parallel on each of these n positional argument combinations, always passing kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute on each worker.
args
The sequences of positional arguments for function.
kwargs
The keyword arguments for function.

Returns

List of return values of the function executions, ordered by the sequence of positional arguments.

push(obj)[source]

Push a copy of obj to all workers of the pool.

A RemoteObject is returned as a handle to the pushed object. This object can be used as a keyword argument to apply, apply_only, map and will then be transparently mapped to the respective copy of the pushed object on the worker.

Immutable objects will be pushed only once. If the same immutable object is pushed a second time, the returned RemoteObject will refer to the already transferred copy. It is therefore safe to use push to ensure that a given immutable object is available on the worker. No unnecessary copies will be created.

Parameters

obj
The object to push to all workers.

Returns

A RemoteObject referring to the pushed data.

scatter_array(U, copy=True)[source]

Distribute VectorArray evenly among the workers.

On each worker a VectorArray is created holding an (up to rounding) equal amount of vectors of U. The returned RemoteObject therefore refers to different data on each of the workers.

Parameters

U
The VectorArray to distribute.
copy
If False, U will be emptied during distribution of the vectors.

Returns

A RemoteObject referring to the scattered data.

scatter_list(l)[source]

Distribute list of objects evenly among the workers.

On each worker a list is created holding an (up to rounding) equal amount of objects of l. The returned RemoteObject therefore refers to different data on each of the workers.

Parameters

l
The list (sequence) of objects to distribute.

Returns

A RemoteObject referring to the scattered data.


class pymor.parallel.dummy.DummyRemoteObject(obj)[source]

Bases: pymor.parallel.interfaces.RemoteObjectInterface

interfaces module
class pymor.parallel.interfaces.RemoteObjectInterface[source]

Bases: object

Handle to remote data on the workers of a WorkerPool.

See documentation of WorkerPoolInterface for usage of these handles in conjunction with apply, scatter_array, scatter_list.

Remote objects can be used as a context manager: when leaving the context, the remote object’s remove method is called to ensure proper cleanup of remote resources.

removed

True, after remove has been called.

remove()[source]

Remove the remote object from the workers.

Remove the object this handle refers to from all workers. Note that the object will only be destroyed if no other object on the worker holds a reference to that object. Moreover, immutable objects will only be destroyed if remove has been called on all RemoteObjects which refer to the object (see push).


class pymor.parallel.interfaces.WorkerPoolInterface[source]

Bases: pymor.core.interfaces.BasicInterface

Interface for parallel worker pools.

WorkerPools allow to easily parallelize algorithms which involve no or little communication between the workers at runtime. The interface methods give the user simple means to distribute data to workers (push, scatter_array, scatter_list) and execute functions on the distributed data in parallel (apply), collecting the return values from each function call. A single worker can be instructed to execute a function using the WorkerPoolInterface.apply_only method. Finally, a parallelized map function is available, which automatically scatters the data among the workers.

All operations are performed synchronously.

__len__()[source]

The number of workers in the pool.

apply(function, *args, **kwargs)[source]

Apply function in parallel on each worker.

This calls function on each worker in parallel, passing args as positional and kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute on each worker.
args
The positional arguments for function.
kwargs
The keyword arguments for function.

Returns

List of return values of the function executions, ordered by worker number (from 0 to len(pool) - 1).

apply_only(function, worker, *args, **kwargs)[source]

Apply function on a single worker.

This calls function on on the worker with number worker, passing args as positional and kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute.
worker
The worker on which to execute the function. (Number between 0 and len(pool) - 1.)
args
The positional arguments for function.
kwargs
The keyword arguments for function.

Returns

Return value of the function execution.

map(function, *args, **kwargs)[source]

Parallel version of the builtin map function.

Each positional argument (after function) must be a sequence of same length n. map calls function in parallel on each of these n positional argument combinations, always passing kwargs as keyword arguments. Keyword arguments which are RemoteObjects are automatically mapped to the respective object on the worker. Moreover, keyword arguments which are immutable objects that have already been pushed to the workers will not be transmitted again. (Immutable objects which have not been pushed before will be transmitted and the remote copy will be destroyed after function execution.)

Parameters

function
The function to execute on each worker.
args
The sequences of positional arguments for function.
kwargs
The keyword arguments for function.

Returns

List of return values of the function executions, ordered by the sequence of positional arguments.

push(obj)[source]

Push a copy of obj to all workers of the pool.

A RemoteObject is returned as a handle to the pushed object. This object can be used as a keyword argument to apply, apply_only, map and will then be transparently mapped to the respective copy of the pushed object on the worker.

Immutable objects will be pushed only once. If the same immutable object is pushed a second time, the returned RemoteObject will refer to the already transferred copy. It is therefore safe to use push to ensure that a given immutable object is available on the worker. No unnecessary copies will be created.

Parameters

obj
The object to push to all workers.

Returns

A RemoteObject referring to the pushed data.

scatter_array(U, copy=True)[source]

Distribute VectorArray evenly among the workers.

On each worker a VectorArray is created holding an (up to rounding) equal amount of vectors of U. The returned RemoteObject therefore refers to different data on each of the workers.

Parameters

U
The VectorArray to distribute.
copy
If False, U will be emptied during distribution of the vectors.

Returns

A RemoteObject referring to the scattered data.

scatter_list(l)[source]

Distribute list of objects evenly among the workers.

On each worker a list is created holding an (up to rounding) equal amount of objects of l. The returned RemoteObject therefore refers to different data on each of the workers.

Parameters

l
The list (sequence) of objects to distribute.

Returns

A RemoteObject referring to the scattered data.

ipython module
class pymor.parallel.ipython.IPythonPool(num_engines=None, **kwargs)[source]

Bases: pymor.parallel.basic.WorkerPoolBase

WorkerPool based on the IPython parallel computing features.

Parameters

num_engines
Number of IPython engines to use. If None, all available engines are used.
kwargs
Keyword arguments used to instantiate the IPython cluster client.
__len__()[source]

The number of workers in the pool.


class pymor.parallel.ipython.RemoteId[source]

Bases: int

Methods

int bit_length, conjugate, from_bytes, to_bytes, __ceil__, __floor__, __new__, __round__, __sizeof__, __trunc__

Attributes

int denominator, imag, numerator, real

class pymor.parallel.ipython.new_ipcluster_pool(profile=None, cluster_id=None, num_engines=None, ipython_dir=None, min_wait=1, timeout=60)[source]

Bases: pymor.core.interfaces.BasicInterface

Create a new IPython parallel cluster and connect to it.

This context manager can be used to create an IPythonPool WorkerPool. When entering the context a new IPython cluster is created using the ipcluster script and an IPythonPool is instantiated for the newly created cluster. When leaving the context the cluster is shut down.

Parameters

profile
Passed as --profile parameter to the ipcluster script.
cluster_id
Passed as --cluster-id parameter to the ipcluster script.
nun_engines
Passed as --n parameter to the ipcluster script.
ipython_dir
Passed as --ipython-dir parameter to the ipcluster script.
min_wait
Wait at least this many seconds before trying to connect to the new cluster.
timeout
Wait at most this many seconds for all Ipython cluster engines to become available.
manager module
class pymor.parallel.manager.RemoteObjectManager[source]

Bases: pymor.core.interfaces.BasicInterface

A simple context manager to keep track of RemoteObjects.

When leaving this context, all RemoteObjects that have been managed by this object will be removed.

manage(remote_object)[source]

Add a RemoteObject to the list of managed objects.

Parameters

remote_object
The object to add to the list.

Returns

remote_object

remove_objects()[source]

Call remove for all managed objects.

pymor.parameters package
Submodules
base module

This module contains the implementation of pyMOR’s parameter handling facilities.

A Parameter in pyMOR is basically a dict of NumPy arrays. Each item of the dict is called a parameter component. The ParameterType of a Parameter is the dict of the shapes of the parameter components, i.e.

mu.parameter_type['component'] == mu['component'].shape

Classes which represent mathematical objects depending on parameters, e.g. Functions, Operators, Discretizations derive from the Parametric mixin. Each Parametric object has a parameter_type attribute holding the ParameterType of the Parameters the object’s evaluate, apply, solve, etc. methods expect. Note that the ParameterType of the given Parameter is allowed to be a superset of the object’s ParameterType.

The ParameterType of a Parametric object is determined in its __init__ method by calling build_parameter_type which computes the ParameterType as the union of the ParameterTypes of the objects given to the method. This way, e.g., an Operator can inherit the ParameterTypes of the data functions it depends upon.

A Parametric object can have a ParameterSpace assigned to it by setting the parameter_space attribute (the ParameterType of the space has to agree with the ParameterType of the object). The parse_parameter method parses a user input according to the object’s ParameterType to make it a Parameter (e.g. if the ParameterType consists of a single one-dimensional component, the user can simply supply a list of numbers of the right length). Moreover, when given a Parameter, parse_parameter ensures the Parameter has an appropriate ParameterType.


class pymor.parameters.base.Parameter(v)[source]

Bases: dict

Class representing a parameter.

A Parameter is simply a dict where each key is a string and each value is a NumPy array. We call an item of the dictionary a parameter component.

A Parameter differs from an ordinary dict in the following ways:

Parameters

v
Anything that dict accepts for the construction of a dictionary.

Methods

Parameter allclose, clear, copy, from_parameter_type, fromkeys, pop, popitem, update
dict get, items, keys, setdefault, values, __contains__, __getitem__, __new__, __sizeof__
parameter_type

The ParameterType of the Parameter.

sid

The state id of the Parameter.

__delitem__(key)[source]

Delete self[key].

__eq__(mu)[source]

Return self==value.

__setitem__(key, value)[source]

Set self[key] to value.

__str__()[source]

Return str(self).

allclose(mu)[source]

Compare two Parameters using float_cmp_all.

Parameters

mu
The Parameter with which to compare.

Returns

True if both Parameters have the same ParameterType and all parameter components are almost equal, else False.

clear() → None. Remove all items from D.[source]
copy() → a shallow copy of D[source]
classmethod from_parameter_type(mu, parameter_type=None)[source]

Takes a user input mu and interprets it as a Parameter according to the given ParameterType.

Depending on the ParameterType, mu can be given as a Parameter, dict, tuple, list, array or scalar.

Parameters

mu
The user input which shall be interpreted as a Parameter.
parameter_type
The ParameterType w.r.t. which mu is to be interpreted.

Returns

The resulting Parameter.

Raises

ValueError
Is raised if mu cannot be interpreted as a Parameter of ParameterType parameter_type.
fromkeys(S, v=None)[source]

Create a new dictionary with keys from iterable and values set to value.

pop(k[, d]) → v, remove specified key and return the corresponding value.[source]

If key is not found, d is returned if given, otherwise KeyError is raised

popitem() → (k, v), remove and return some (key, value) pair as a[source]

2-tuple; but raise KeyError if D is empty.

update([E, ]**F) → None. Update D from dict/iterable E and F.[source]

If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]


class pymor.parameters.base.ParameterType(t)[source]

Bases: collections.OrderedDict

Class representing a parameter type.

A parameter type is simply a dictionary with strings as keys and tuples of natural numbers as values. The keys are the names of the parameter components and the tuples their expected shape (compare Parameter).

Apart from checking the correct format of its values, the only difference between a ParameterType and an ordinary dict is, that ParameterType orders its keys alphabetically.

Parameters

t
If t is an object with a parameter_type attribute, a copy of this ParameterType is created. Otherwise, t can be anything from which a dict can be constructed.

Methods

ParameterType copy, fromkeys
OrderedDict clear, items, keys, move_to_end, pop, popitem, setdefault, update, values, __reversed__
dict get, __contains__, __getitem__, __new__

Attributes

ParameterType sid
__hash__()[source]

Return hash(self).

__reduce__()[source]

Return state information for pickling

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

copy() → a shallow copy of od[source]
fromkeys(S, v=None)[source]

Create a new ordered dictionary with keys from iterable and values set to value.


class pymor.parameters.base.Parametric[source]

Bases: object

Mixin class for objects representing mathematical entities depending on a Parameter.

Each such object has a ParameterType stored in the parameter_type attribute, which should be set by the implementor during __init__ using the build_parameter_type method. Methods expecting the Parameter (typically evaluate, apply, solve, etc. ..) should accept an optional argument mu defaulting to None. This argument mu should then be fed into parse_parameter to obtain a Parameter of correct ParameterType from the (user supplied) input mu.

parameter_type

The ParameterType of the Parameters the object expects.

parameter_space

ParameterSpace the parameters are expected to lie in or None.

parametric

True if the object really depends on a parameter, i.e. parameter_type is not empty.

build_parameter_type(*args, provides=None, **kwargs)[source]

Builds the ParameterType of the object. Should be called by __init__.

The ParameterType of a Parametric object is determined by the parameter components the object itself requires for evaluation, and by the parameter components required by the objects the object depends upon for evaluation.

All parameter components (directly specified or inherited by the ParameterType of a given Parametric object) with the same name are treated as identical and are thus required to have the same shapes. The object’s ParameterType is then made up by the shapes of all parameter components appearing.

Additionally components of the resulting ParameterType can be removed by specifying them via the provides parameter. The idea is that the object itself may provide parameter components to the inherited objects which thus should not become part of the object’s own parameter type. (A typical application would be InstationaryDiscretization, which provides a time parameter component to its (time-dependent) operators during time-stepping.)

Parameters

args
Each positional argument must either be a dict of parameter components and shapes or a Parametric object whose parameter_type is added.
kwargs
Each keyword argument is interpreted as parameter component with corresponding shape.
provides
Dict of parameter component names and shapes which are provided by the object itself. The parameter components listed here will not become part of the object’s ParameterType.
parse_parameter(mu)[source]

Interpret a user supplied parameter mu as a Parameter.

If mu is not already a Parameter, Parameter.from_parameter_type is used, to make mu a parameter of the correct ParameterType. If mu is already a Parameter, it is checked if its ParameterType matches our own. (It is actually allowed that the ParameterType of mu is a superset of our own ParameterType in the obvious sense.)

Parameters

mu
The input to parse as a Parameter.
strip_parameter(mu)[source]

Remove all components of the Parameter mu which are not part of the object’s ParameterType.

Otherwise strip_parameter behaves like parse_parameter.

This method is mainly useful for caching where the key should only contain the relevant parameter components.

functionals module
class pymor.parameters.functionals.ExpressionParameterFunctional(expression, parameter_type, name=None)[source]

Bases: pymor.parameters.functionals.GenericParameterFunctional

Turns a Python expression given as a string into a ParameterFunctional.

Some NumPy arithmetic functions like sin, log, min are supported. For a full list see the functions class attribute.

Warning

eval is used to evaluate the given expression. Using this class with expression strings from untrusted sources will cause mayhem and destruction!

Parameters

expression
A Python expression in the parameter components of the given parameter_type.
parameter_type
The ParameterType of the Parameters the functional expects.
name
The name of the functional.
__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).


class pymor.parameters.functionals.GenericParameterFunctional(mapping, parameter_type, name=None)[source]

Bases: pymor.parameters.interfaces.ParameterFunctionalInterface

A wrapper making an arbitrary Python function a ParameterFunctional

Note that a GenericParameterFunctional can only be pickled if the function it is wrapping can be pickled. For this reason, it is usually preferable to use ExpressionParameterFunctional instead of GenericParameterFunctional.

Parameters

mapping
The function to wrap. The function has signature mapping(mu).
parameter_type
The ParameterType of the Parameters the functional expects.
name
The name of the functional.
evaluate(mu=None)[source]

Evaluate the functional for the given Parameter mu.


class pymor.parameters.functionals.ProductParameterFunctional(factors, name=None)[source]

Bases: pymor.parameters.interfaces.ParameterFunctionalInterface

Forms the product of a list of ParameterFunctionals or numbers.

Parameters

factors
A list of ParameterFunctionals or numbers.
name
Name of the functional.
evaluate(mu=None)[source]

Evaluate the functional for the given Parameter mu.


class pymor.parameters.functionals.ProjectionParameterFunctional(component_name, component_shape, coordinates=(), name=None)[source]

Bases: pymor.parameters.interfaces.ParameterFunctionalInterface

ParameterFunctional returning a component of the given parameter.

For given parameter mu, this functional evaluates to

mu[component_name][coordinates]

Parameters

component_name
The name of the parameter component to return.
component_shape
The shape of the parameter component.
coordinates
See above.
name
Name of the functional.
evaluate(mu=None)[source]

Evaluate the functional for the given Parameter mu.

spaces module
class pymor.parameters.spaces.CubicParameterSpace(parameter_type, minimum=None, maximum=None, ranges=None)[source]

Bases: pymor.parameters.interfaces.ParameterSpaceInterface

Simple ParameterSpace where each summand is an n-cube.

Parameters

parameter_type
The ParameterType of the space.
minimum
The minimum for each matrix entry of each Parameter component. Must be None if ranges is specified.
maximum
The maximum for each matrix entry of each Parameter component. Must be None if ranges is specified.
ranges
dict whose keys agree with parameter_type and whose values are tuples (min, max) specifying the minimum and maximum of each matrix entry of corresponding Parameter component. Must be None if minimum and maximum are specified.
__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

contains(mu)[source]

True if mu is contained in the space.

sample_randomly(count=None, random_state=None, seed=None)[source]

Randomly sample Parameters from the space.

Warning

When neither random_state nor seed are specified, repeated calls to this method will return the same sequence of parameters!

Parameters

count
None or number of random parameters (see below).
random_state
RandomState to use for sampling. If None, a new random state is generated using seed as random seed.
seed
Random seed to use. If None, the default random seed is used.

Returns

If count is None, an inexhaustible iterator returning random Parameters. Otherwise a list of count random Parameters.

sample_uniformly(counts)[source]

Uniformly sample Parameters from the space.

pymor.playground package
Subpackages
pymor.playground.core package
Submodules
network_cache module
class pymor.playground.core.network_cache.NetworkFilesystemRegion(server_path, secret='')[source]

Bases: pymor.core.cache.CacheRegion

clear()[source]

Clear the entire cache region.

get(key)[source]

Return cache entry for given key.

Parameters

key
The key for the cache entry.

Returns

(True, entry)
in case the key has been found in the cache region.
(False, None)
in case the key is not present in the cache region.
set(key, value)[source]

Set cache entry for key to given value.

This method is usually called only once for any given key (with the exemption of issues due to concurrency).


class pymor.playground.core.network_cache.NetworkFilesystemRegionServer(addr, path, secret=None)[source]

Bases: pymor.core.interfaces.BasicInterface

pymor.playground.discretizers package
Submodules
numpylistvectorarray module
pymor.playground.discretizers.numpylistvectorarray.convert_to_numpy_list_vector_array(d)[source]

Use NumpyListVectorArrayMatrixOperator instead of NumpyMatrixOperator.

This simple function converts linear, affinely decomposed discretizations to use NumpyListVectorArrayMatrixOperator instead of NumpyMatrixOperator.

pymor.playground.functions package
Submodules
expression_function module
class pymor.playground.functions.expression_function.ExpressionFunction(expressions, variables='x y z')[source]

Bases: pymor.core.interfaces.BasicInterface

__call__(domain_vec)[source]

Call self as a function.

pymor.playground.operators package
Submodules
numpy module
class pymor.playground.operators.numpy.NumpyListVectorArrayMatrixOperator(matrix, source_id=None, range_id=None, solver_options=None, name=None)[source]

Bases: pymor.operators.numpy.NumpyMatrixOperator

Variant of NumpyMatrixOperator using ListVectorArray instead of NumpyVectorArray.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.

apply_adjoint(V, mu=None)[source]

Apply the adjoint operator.

For any given linear Operator op, Parameter mu and VectorArrays U, V in the source resp. range we have:

op.apply_adjoint(V, mu).dot(U) == V.dot(op.apply(U, mu))

Thus, when op is represented by a matrix M, apply_adjoint is given by left-multplication of (the complex conjugate of) M with V.

Parameters

V
VectorArray of vectors to which the adjoint operator is applied.
mu
The Parameter for which to apply the adjoint operator.

Returns

VectorArray of the adjoint operator evaluations.

apply_inverse(V, mu=None, least_squares=False)[source]

Apply the inverse operator.

Parameters

V
VectorArray of vectors to which the inverse operator is applied.
mu
The Parameter for which to evaluate the inverse operator.
least_squares

If True, solve the least squares problem:

u = argmin ||op(u) - v||_2.

Since for an invertible operator the least squares solution agrees with the result of the application of the inverse operator, setting this option should, in general, have no effect on the result for those operators. However, note that when no appropriate solver_options are set for the operator, most implementations will choose a least squares solver by default which may be undesirable.

check_finite
Test if solution only contains finite values.
default_sparse_solver_backend
Default sparse solver backend to use (scipy, pyamg, generic).

Returns

VectorArray of the inverse operator evaluations.

Raises

InversionError
The operator could not be inverted.

Defaults

check_finite, default_sparse_solver_backend (see pymor.core.defaults)

as_range_array(mu=None)[source]

Return a VectorArray representation of the operator in its range space.

In the case of a linear operator with NumpyVectorSpace as source, this method returns for every Parameter mu a VectorArray V in the operator’s range, such that

V.lincomb(U.to_numpy()) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
as_source_array(mu=None)[source]

Return a VectorArray representation of the operator in its source space.

In the case of a linear operator with NumpyVectorSpace as range, this method returns for every Parameter mu a VectorArray V in the operator’s source, such that

self.range.make_array(V.dot(U).T) == self.apply(U, mu)

for all VectorArrays U.

Parameters

mu
The Parameter for which to return the VectorArray representation.

Returns

V
The VectorArray defined above.
assemble_lincomb(operators, coefficients, solver_options=None, name=None)[source]

Try to assemble a linear combination of the given operators.

This method is called in the assemble method of LincombOperator on the first of its operators. If an assembly of the given linear combination is possible, e.g. the linear combination of the system matrices of the operators can be formed, then the assembled operator is returned. Otherwise, the method returns None to indicate that assembly is not possible.

Parameters

operators
List of Operators whose linear combination is formed.
coefficients
List of the corresponding linear coefficients.
solver_options
solver_options for the assembled operator.
name
Name of the assembled operator.

Returns

The assembled Operator if assembly is possible, otherwise None.

pymor.playground.vectorarrays package
Submodules
mpi module
pymor.playground.vectorarrays.mpi.random_array(dims, length, seed)[source]
pymor.reductors package
Submodules
basic module
class pymor.reductors.basic.GenericPGReductor(d, W, V, bases_are_biorthonormal, vector_ranged_operators=('initial_data', ), product=None)[source]

Bases: pymor.core.interfaces.BasicInterface

Generic Petrov-Galerkin reductor.

Replaces each Operator of the given Discretization with the projection onto the span of the given projection matrices.

Parameters

d
The Discretization which is to be reduced.
W
VectorArray containing the left projection matrix.
V
VectorArray containing the right projection matrix.
bases_are_biorthonormal
Indicate whether or not V and W are biorthonormal w.r.t. product.
vector_ranged_operators
List of keys in d.operators for which the corresponding Operator should be biorthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals).
product
Inner product for the projection of the Operators given by vector_ranged_operators.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce()[source]

Perform the Petrov-Galerkin projection.

Returns

The reduced Discretization.


class pymor.reductors.basic.GenericRBReductor(d, RB=None, basis_is_orthonormal=None, vector_ranged_operators=('initial_data', ), product=None)[source]

Bases: pymor.core.interfaces.BasicInterface

Generic reduced basis reductor.

Replaces each Operator of the given Discretization with the Galerkin projection onto the span of the given reduced basis.

Parameters

d
The Discretization which is to be reduced.
RB
VectorArray containing the reduced basis on which to project.
basis_is_orthonormal
If RB is specified, indicate whether or not the basis is orthonormal w.r.t. product.
vector_ranged_operators
List of keys in d.operators for which the corresponding Operator should be orthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals).
product
Inner product for the orthonormalization of RB and the projection of the Operators given by vector_ranged_operators.
extend_basis(U, method='gram_schmidt', pod_modes=1, pod_orthonormalize=True, orthonormal=None, copy_U=True)[source]

Extend basis by new vectors.

Parameters

U
VectorArray containing the new basis vectors.
method

Basis extension method to use. The following methods are available:

trivial:Vectors in U are appended to the basis. Duplicate vectors in the sense of almost_equal are removed.
gram_schmidt:New basis vectors are orthonormalized w.r.t. to the old basis using the gram_schmidt algorithm.
pod:Append the first POD modes of the defects of the projections of the vectors in U onto the existing basis (e.g. for use in POD-Greedy algorithm).

Warning

In case of the 'gram_schmidt' and 'pod' extension methods, the existing reduced basis is assumed to be orthonormal w.r.t. the given inner product.

pod_modes
In case method == 'pod', the number of POD modes that shall be appended to the basis.
pod_orthonormalize
If True and method == 'pod', re-orthonormalize the new basis vectors obtained by the POD in order to improve numerical accuracy.
orthonormal
If method == 'trivial', set this to True to indicate that the basis will remain orthonormal after extending.
copy_U
If copy_U is False, the new basis vectors might be removed from U.

Raises

ExtensionError
Raised when the selected extension method does not yield a basis of increased dimension.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(dim=None)[source]

Perform the reduced basis projection.

Parameters

dim
If specified, the desired reduced state dimension. Must not be larger than the current reduced basis dimension.

Returns

The reduced Discretization.


pymor.reductors.basic.extend_basis(basis, U, product=None, method='gram_schmidt', pod_modes=1, pod_orthonormalize=True, copy_U=True)[source]
bt module
class pymor.reductors.bt.BRBTReductor(d, gamma, solver_options=None)[source]

Bases: pymor.reductors.bt.GenericBTReductor

Bounded Real (BR) Balanced Truncation reductor.

See [A05] (Section 7.5.3) and [OJ88].

Parameters

d
The system which is to be reduced.
gamma
Upper bound for the \mathcal{H}_\infty-norm.
solver_options
The solver options to use to solve the positive Riccati equations.
error_bounds()[source]

Returns error bounds for all possible reduced orders.

gramians()[source]

Return low-rank Cholesky factors of Gramians.


class pymor.reductors.bt.BTReductor(d)[source]

Bases: pymor.reductors.bt.GenericBTReductor

Standard (Lyapunov) Balanced Truncation reductor.

See Section 7.3 in [A05].

Parameters

d
The system which is to be reduced.
error_bounds()[source]

Returns error bounds for all possible reduced orders.

gramians()[source]

Return low-rank Cholesky factors of Gramians.


class pymor.reductors.bt.GenericBTReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Generic Balanced Truncation reductor.

Parameters

d
The system which is to be reduced.
error_bounds()[source]

Returns error bounds for all possible reduced orders.

gramians()[source]

Return low-rank Cholesky factors of Gramians.

reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(r=None, tol=None, projection='bfsr')[source]

Generic Balanced Truncation.

Parameters

r
Order of the reduced model if tol is None, maximum order if tol is specified.
tol
Tolerance for the error bound if r is None.
projection

Projection method used:

  • 'sr': square root method
  • 'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)
  • 'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices (using gram_schmidt_biorth)

Returns

rd
Reduced system.
sv_U_V()[source]

Return singular values and vectors.


class pymor.reductors.bt.LQGBTReductor(d, solver_options=None)[source]

Bases: pymor.reductors.bt.GenericBTReductor

Linear Quadratic Gaussian (LQG) Balanced Truncation reductor.

See Section 3 in [MG91].

Parameters

d
The system which is to be reduced.
solver_options
The solver options to use to solve the Riccati equations.
error_bounds()[source]

Returns error bounds for all possible reduced orders.

gramians()[source]

Return low-rank Cholesky factors of Gramians.

coercive module
class pymor.reductors.coercive.CoerciveRBEstimator(residual, residual_range_dims, coercivity_estimator)[source]

Bases: pymor.core.interfaces.ImmutableInterface

Instantiated by CoerciveRBReductor.

Not to be used directly.


class pymor.reductors.coercive.CoerciveRBReductor(d, RB=None, basis_is_orthonormal=None, vector_ranged_operators=('initial_data', ), product=None, coercivity_estimator=None)[source]

Bases: pymor.reductors.basic.GenericRBReductor

Reduced Basis reductor for StationaryDiscretizations with coercive linear operator.

The only addition to GenericRBReductor is an error estimator which evaluates the dual norm of the residual with respect to a given inner product. For the reduction of the residual we use ResidualReductor for improved numerical stability [BEOR14].

Parameters

d
The Discretization which is to be reduced.
RB
VectorArray containing the reduced basis on which to project.
basis_is_orthonormal
If RB is specified, indicate whether or not the basis is orthonormal w.r.t. product.
vector_ranged_operators
List of keys in d.operators for which the corresponding Operator should be orthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals).
product
Inner product for the orthonormalization of RB, the projection of the Operators given by vector_ranged_operators and for the computation of Riesz representatives of the residual. If None, the Euclidean product is used.
coercivity_estimator
None or a ParameterFunctional returning a lower bound for the coercivity constant of the given problem. Note that the computed error estimate is only guaranteed to be an upper bound for the error when an appropriate coercivity estimate is specified.

class pymor.reductors.coercive.SimpleCoerciveRBEstimator(estimator_matrix, coercivity_estimator)[source]

Bases: pymor.core.interfaces.ImmutableInterface

Instantiated by SimpleCoerciveRBReductor.

Not to be used directly.


class pymor.reductors.coercive.SimpleCoerciveRBReductor(d, RB=None, basis_is_orthonormal=None, vector_ranged_operators=('initial_data', ), product=None, coercivity_estimator=None)[source]

Bases: pymor.reductors.basic.GenericRBReductor

Reductor for linear StationaryDiscretizations with affinely decomposed operator and rhs.

Note

The reductor CoerciveRBReductor can be used for arbitrary coercive StationaryDiscretizations and offers an improved error estimator with better numerical stability.

The only addition is to GenericRBReductor is an error estimator, which evaluates the norm of the residual with respect to a given inner product.

Parameters

d
The Discretization which is to be reduced.
RB
VectorArray containing the reduced basis on which to project.
basis_is_orthonormal
If RB is specified, indicate whether or not the basis is orthonormal w.r.t. product.
vector_ranged_operators
List of keys in d.operators for which the corresponding Operator should be orthogonally projected (i.e. operators which map to vectors in contrast to bilinear forms which map to functionals).
product
Inner product for the orthonormalization of RB, the projection of the Operators given by vector_ranged_operators and for the computation of Riesz representatives of the residual. If None, the Euclidean product is used.
coercivity_estimator
None or a ParameterFunctional returning a lower bound for the coercivity constant of the given problem. Note that the computed error estimate is only guaranteed to be an upper bound for the error when an appropriate coercivity estimate is specified.
h2 module
class pymor.reductors.h2.IRKAReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Iterative Rational Krylov Algorithm reductor.

Parameters

d
LTISystem.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(r, sigma=None, b=None, c=None, rd0=None, tol=0.0001, maxit=100, num_prev=1, force_sigma_in_rhp=False, projection='orth', use_arnoldi=False, conv_crit='sigma', compute_errors=False)[source]

Reduce using IRKA.

See [GAB08] (Algorithm 4.1) and [ABG10] (Algorithm 1).

Parameters

r
Order of the reduced order model.
sigma

Initial interpolation points (closed under conjugation).

If None, interpolation points are log-spaced between 0.1 and 10. If sigma is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a one-dimensional array-like of length r.

sigma and rd0 cannot both be not None.

b

Initial right tangential directions.

If None, if is chosen as all ones. If b is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a VectorArray of length r from d.B.source.

b and rd0 cannot both be not None.

c

Initial left tangential directions.

If None, if is chosen as all ones. If c is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a VectorArray of length r from d.C.range.

c and rd0 cannot both be not None.

rd0

Initial reduced order model.

If None, then sigma, b, and c are used. Otherwise, it needs to be an LTISystem of order r and it is used to construct sigma, b, and c.

tol
Tolerance for the convergence criterion.
maxit
Maximum number of iterations.
num_prev
Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of IRKA.
force_sigma_in_rhp
If False, new interpolation are reflections of the current reduced order model’s poles. Otherwise, only poles in the left half-plane are reflected.
projection

Projection method:

  • 'orth': projection matrices are orthogonalized with respect to the Euclidean inner product
  • 'biorth': projection matrices are biorthogolized with respect to the E product
use_arnoldi
Should the Arnoldi process be used for rational interpolation. Available only for SISO systems. Otherwise, it is ignored.
conv_crit

Convergence criterion:

  • 'sigma': relative change in interpolation points
  • 'h2': relative \mathcal{H}_2 distance of reduced-order models
compute_errors

Should the relative \mathcal{H}_2-errors of intermediate reduced order models be computed.

Warning

Computing \mathcal{H}_2-errors is expensive. Use this option only if necessary.

Returns

rd
Reduced LTISystem model.

class pymor.reductors.h2.TF_IRKAReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Realization-independent IRKA reductor.

See [BG12].

Parameters

d
Discretization with eval_tf and eval_dtf methods.
reduce(r, sigma=None, b=None, c=None, rd0=None, tol=0.0001, maxit=100, num_prev=1, force_sigma_in_rhp=False, conv_crit='sigma')[source]

Reduce using TF-IRKA.

Parameters

r
Order of the reduced order model.
sigma

Initial interpolation points (closed under conjugation).

If None, interpolation points are log-spaced between 0.1 and 10. If sigma is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a one-dimensional array-like of length r.

sigma and rd0 cannot both be not None.

b

Initial right tangential directions.

If None, if is chosen as all ones. If b is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a NumPy array of shape (m, r).

b and rd0 cannot both be not None.

c

Initial left tangential directions.

If None, if is chosen as all ones. If c is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a NumPy array of shape (p, r).

c and rd0 cannot both be not None.

rd0

Initial reduced order model.

If None, then sigma, b, and c are used. Otherwise, it needs to be an LTISystem of order r and it is used to construct sigma, b, and c.

tol
Tolerance for the convergence criterion.
maxit
Maximum number of iterations.
num_prev
Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of TF-IRKA.
force_sigma_in_rhp
If False, new interpolation are reflections of the current reduced order model’s poles. Otherwise, only the poles in the left half-plane are reflected.
conv_crit

Convergence criterion:

  • 'sigma': relative change in interpolation points
  • 'h2': relative \mathcal{H}_2 distance of reduced-order models

Returns

rd
Reduced LTISystem model.

class pymor.reductors.h2.TSIAReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Two-Sided Iteration Algorithm reductor.

Parameters

d
LTISystem.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(rd0, tol=0.0001, maxit=100, num_prev=1, projection='orth', conv_crit='sigma', compute_errors=False)[source]

Reduce using TSIA.

See [XZ11] (Algorithm 1) and [BKS11].

In exact arithmetic, TSIA is equivalent to IRKA (under some assumptions on the poles of the reduced model). The main difference in implementation is that TSIA computes the Schur decomposition of the reduced matrices, while IRKA computes the eigenvalue decomposition. Therefore, TSIA might behave better for non-normal reduced matrices.

Parameters

rd0
Initial reduced order model.
tol
Tolerance for the convergence criterion.
maxit
Maximum number of iterations.
num_prev
Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of TSIA.
projection

Projection method:

  • 'orth': projection matrices are orthogonalized with respect to the Euclidean inner product
  • 'biorth': projection matrices are biorthogolized with respect to the E product
conv_crit

Convergence criterion:

  • 'sigma': relative change in interpolation points
  • 'h2': relative \mathcal{H}_2 distance of reduced-order models
compute_errors

Should the relative \mathcal{H}_2-errors of intermediate reduced order models be computed.

Warning

Computing \mathcal{H}_2-errors is expensive. Use this option only if necessary.

Returns

rd
Reduced LTISystem.

pymor.reductors.h2._convergence_criterion(data, conv_crit)[source]

Compute the convergence criterion for given data.


pymor.reductors.h2._poles_and_tangential_directions(rd)[source]

Compute the poles and tangential directions of a reduced order model.

interpolation module
class pymor.reductors.interpolation.GenericBHIReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Generic bitangential Hermite interpolation reductor.

This is a generic reductor for reducing any linear InputStateOutputSystem with the transfer function which can be written in the generalized coprime factorization \mathcal{C}(s) \mathcal{K}(s)^{-1}
\mathcal{B}(s) as in [BG09]. The interpolation here is limited to only up to the first derivative. Hence, interpolation points are assumed to be pairwise distinct.

Parameters

d
Discretization.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(sigma, b, c, projection='orth')[source]

Bitangential Hermite interpolation.

Parameters

sigma
Interpolation points (closed under conjugation), list of length r.
b
Right tangential directions, VectorArray of length r from self.d.input_space.
c
Left tangential directions, VectorArray of length r from self.d.output_space.
projection

Projection method:

  • 'orth': projection matrices are orthogonalized with respect to the Euclidean inner product
  • 'biorth': projection matrices are biorthogolized with respect to the E product

Returns

rd
Reduced discretization.

class pymor.reductors.interpolation.LTI_BHIReductor(d)[source]

Bases: pymor.reductors.interpolation.GenericBHIReductor

Bitangential Hermite interpolation for LTISystems.

Parameters

d
LTISystem.
reduce(sigma, b, c, projection='orth', use_arnoldi=False)[source]

Bitangential Hermite interpolation.

Parameters

sigma
Interpolation points (closed under conjugation), list of length r.
b
Right tangential directions, VectorArray of length r from self.d.input_space.
c
Left tangential directions, VectorArray of length r from self.d.output_space.
projection

Projection method:

  • 'orth': projection matrices are orthogonalized with respect to the Euclidean inner product
  • 'biorth': projection matrices are biorthogolized with respect to the E product
use_arnoldi
Should the Arnoldi process be used for rational interpolation. Available only for SISO systems. Otherwise, it is ignored.

Returns

rd
Reduced discretization.
reduce_arnoldi(sigma, b, c)[source]

Bitangential Hermite interpolation for SISO LTISystems.

Parameters

sigma
Interpolation points (closed under conjugation), list of length r.
b
Right tangential directions, VectorArray of length r from self.d.B.source.
c
Left tangential directions, VectorArray of length r from self.d.C.range.

Returns

rd
Reduced LTISystem model.

class pymor.reductors.interpolation.SO_BHIReductor(d)[source]

Bases: pymor.reductors.interpolation.GenericBHIReductor

Bitangential Hermite interpolation for second-order systems.

Parameters

d
SecondOrderSystem.

class pymor.reductors.interpolation.TFInterpReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Loewner bitangential Hermite interpolation reductor.

See [BG12].

Parameters

d
Discretization with eval_tf and eval_dtf methods.
reduce(sigma, b, c)[source]

Realization-independent tangential Hermite interpolation.

Parameters

sigma
Interpolation points (closed under conjugation), list of length r.
b
Right tangential directions, NumPy array of shape (d.m, r).
c
Left tangential directions, NumPy array of shape (d.p, r).

Returns

lti
LTISystem interpolating the transfer function of d.
parabolic module
class pymor.reductors.parabolic.ParabolicRBEstimator(residual, residual_range_dims, initial_residual, initial_residual_range_dims, coercivity_estimator)[source]

Bases: pymor.core.interfaces.ImmutableInterface

Instantiated by ParabolicRBReductor.

Not to be used directly.


class pymor.reductors.parabolic.ParabolicRBReductor(d, RB=None, basis_is_orthonormal=None, product=None, coercivity_estimator=None)[source]

Bases: pymor.reductors.basic.GenericRBReductor

Reduced Basis Reductor for parabolic equations.

This reductor uses GenericRBReductor for the actual RB-projection. The only addition is the assembly of an error estimator which bounds the discrete l2-in time / energy-in space error similar to [GP05], [HO08] as follows:

\left[ C_a^{-1}(\mu)\|e_N(\mu)\|^2 + \sum_{n=1}^{N} \Delta t\|e_n(\mu)\|^2_e \right]^{1/2}
    \leq \left[ C_a^{-1}(\mu)\Delta t \sum_{n=1}^{N}\|\mathcal{R}^n(u_n(\mu), \mu)\|^2_{e,-1}
                + C_a^{-1}(\mu)\|e_0\|^2 \right]^{1/2}

Here, \|\cdot\| denotes the norm induced by the problem’s mass matrix (e.g. the L^2-norm) and \|\cdot\|_e is an arbitrary energy norm w.r.t. which the space operator A(\mu) is coercive, and C_a(\mu) is a lower bound for its coercivity constant. Finally, \mathcal{R}^n denotes the implicit Euler timestepping residual for the (fixed) time step size \Delta t,

\mathcal{R}^n(u_n(\mu), \mu) :=
    f - M \frac{u_{n}(\mu) - u_{n-1}(\mu)}{\Delta t} - A(u_n(\mu), \mu),

where M denotes the mass operator and f the source term. The dual norm of the residual is computed using the numerically stable projection from [BEOR14].

Parameters

d
The InstationaryDiscretization which is to be reduced.
RB
VectorArray containing the reduced basis on which to project.
basis_is_orthonormal
Indicate whether or not the basis is orthonormal w.r.t. product.
product
The energy inner product Operator w.r.t. which the reduction error is estimated and RB is orthonormalized.
coercivity_estimator
None or a ParameterFunctional returning a lower bound C_a(\mu) for the coercivity constant of d.operator w.r.t. product.
residual module
class pymor.reductors.residual.ImplicitEulerResidualOperator(operator, mass, rhs, dt, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Instantiated by ImplicitEulerResidualReductor.

apply(U, U_old, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.


class pymor.reductors.residual.ImplicitEulerResidualReductor(RB, operator, mass, dt, rhs=None, product=None)[source]

Bases: pymor.core.interfaces.BasicInterface

Reduced basis residual reductor with mass operator for implicit Euler timestepping.

Given an operator, mass and a functional, the concatenation of residual operator with the Riesz isomorphism is given by:

riesz_residual.apply(U, U_old, mu)
    == product.apply_inverse(operator.apply(U, mu) + 1/dt*mass.apply(U, mu) - 1/dt*mass.apply(U_old, mu)
       - rhs.as_vector(mu))

This reductor determines a low-dimensional subspace of the image of a reduced basis space under riesz_residual using estimate_image_hierarchical, computes an orthonormal basis residual_range of this range space and then returns the Petrov-Galerkin projection

projected_riesz_residual
    == riesz_residual.projected(range_basis=residual_range, source_basis=RB)

of the riesz_residual operator. Given reduced basis coefficient vectors u and u_old, the dual norm of the residual can then be computed as

projected_riesz_residual.apply(u, u_old, mu).l2_norm()

Moreover, a reconstruct method is provided such that

residual_reductor.reconstruct(projected_riesz_residual.apply(u, u_old, mu))
    == riesz_residual.apply(RB.lincomb(u), RB.lincomb(u_old), mu)

Parameters

operator
See definition of riesz_residual.
mass
The mass operator. See definition of riesz_residual.
dt
The time step size. See definition of riesz_residual.
rhs
See definition of riesz_residual. If None, zero right-hand side is assumed.
RB
VectorArray containing a basis of the reduced space onto which to project.
product
Inner product Operator w.r.t. which to compute the Riesz representatives.
reconstruct(u)[source]

Reconstruct high-dimensional residual vector from reduced vector u.


class pymor.reductors.residual.NonProjectedImplicitEulerResidualOperator(operator, mass, rhs, dt, product)[source]

Bases: pymor.reductors.residual.ImplicitEulerResidualOperator

Instantiated by ImplicitEulerResidualReductor.

Not to be used directly.

apply(U, U_old, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.


class pymor.reductors.residual.NonProjectedResidualOperator(operator, rhs, riesz_representatives, product)[source]

Bases: pymor.reductors.residual.ResidualOperator

Instantiated by ResidualReductor.

Not to be used directly.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.


class pymor.reductors.residual.ResidualOperator(operator, rhs, name=None)[source]

Bases: pymor.operators.basic.OperatorBase

Instantiated by ResidualReductor.

apply(U, mu=None)[source]

Apply the operator to a VectorArray.

Parameters

U
VectorArray of vectors to which the operator is applied.
mu
The Parameter for which to evaluate the operator.

Returns

VectorArray of the operator evaluations.


class pymor.reductors.residual.ResidualReductor(RB, operator, rhs=None, product=None, riesz_representatives=False)[source]

Bases: pymor.core.interfaces.BasicInterface

Generic reduced basis residual reductor.

Given an operator and a right-hand side, the residual is given by:

residual.apply(U, mu) == operator.apply(U, mu) - rhs.as_range_array(mu)

When operator maps to functionals instead of vectors, we are interested in the Riesz representative of the residual:

residual.apply(U, mu)
    == product.apply_inverse(operator.apply(U, mu) - rhs.as_range_array(mu))

Given a basis RB of a subspace of the source space of operator, this reductor uses estimate_image_hierarchical to determine a low-dimensional subspace containing the image of the subspace under residual (resp. riesz_residual), computes an orthonormal basis residual_range for this range space and then returns the Petrov-Galerkin projection

projected_residual
    == project(residual, range_basis=residual_range, source_basis=RB)

of the residual operator. Given a reduced basis coefficient vector u, w.r.t. RB, the (dual) norm of the residual can then be computed as

projected_residual.apply(u, mu).l2_norm()

Moreover, a reconstruct method is provided such that

residual_reductor.reconstruct(projected_residual.apply(u, mu))
    == residual.apply(RB.lincomb(u), mu)

Parameters

RB
VectorArray containing a basis of the reduced space onto which to project.
operator
See definition of residual.
rhs
See definition of residual. If None, zero right-hand side is assumed.
product
Inner product Operator w.r.t. which to orthonormalize and w.r.t. which to compute the Riesz representatives in case operator maps to functionals.
riesz_representatives
If True compute the Riesz representative of the residual.
reconstruct(u)[source]

Reconstruct high-dimensional residual vector from reduced vector u.

sobt module
class pymor.reductors.sobt.GenericSOBTpvReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Generic Second-Order Balanced Truncation position/velocity reductor.

See [RS08].

Parameters

d
The system which is to be reduced.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(r, projection='bfsr')[source]

Reduce using GenericSOBTpv.

Parameters

r
Order of the reduced model.
projection

Projection method used:

  • 'sr': square root method
  • 'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)
  • 'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices

Returns

rd
Reduced system.

class pymor.reductors.sobt.SOBTReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Second-Order Balanced Truncation reductor.

See [CLVV06].

Parameters

d
The system which is to be reduced.
reduce(r, projection='bfsr')[source]

Reduce using SOBT.

Parameters

r
Order of the reduced model.
projection

Projection method used:

  • 'sr': square root method
  • 'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)
  • 'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices

Returns

rd
Reduced system.

class pymor.reductors.sobt.SOBTfvReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

Free-velocity Second-Order Balanced Truncation reductor.

See [MS96].

Parameters

d
The system which is to be reduced.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(r, projection='bfsr')[source]

Reduce using SOBTfv.

Parameters

r
Order of the reduced model.
projection

Projection method used:

  • 'sr': square root method
  • 'bfsr': balancing-free square root method (default, since it avoids scaling by singular values and orthogonalizes the projection matrices, which might make it more accurate than the square root method)
  • 'biorth': like the balancing-free square root method, except it biorthogonalizes the projection matrices

Returns

rd
Reduced system.

class pymor.reductors.sobt.SOBTpReductor(d)[source]

Bases: pymor.reductors.sobt.GenericSOBTpvReductor

Second-Order Balanced Truncation position reductor.

See [RS08].

Parameters

d
The system which is to be reduced.

class pymor.reductors.sobt.SOBTpvReductor(d)[source]

Bases: pymor.reductors.sobt.GenericSOBTpvReductor

Second-Order Balanced Truncation position-velocity reductor.

See [RS08].

Parameters

d
The system which is to be reduced.

class pymor.reductors.sobt.SOBTvReductor(d)[source]

Bases: pymor.reductors.sobt.GenericSOBTpvReductor

Second-Order Balanced Truncation velocity reductor.

See [RS08].

Parameters

d
The system which is to be reduced.

class pymor.reductors.sobt.SOBTvpReductor(d)[source]

Bases: pymor.reductors.sobt.GenericSOBTpvReductor

Second-Order Balanced Truncation velocity-position reductor.

See [RS08].

Parameters

d
The system which is to be reduced.
sor_irka module
class pymor.reductors.sor_irka.SOR_IRKAReductor(d)[source]

Bases: pymor.core.interfaces.BasicInterface

SOR-IRKA reductor.

Parameters

d
SecondOrderSystem.
reconstruct(u)[source]

Reconstruct high-dimensional vector from reduced vector u.

reduce(r, sigma=None, b=None, c=None, rd0=None, tol=0.0001, maxit=100, num_prev=1, force_sigma_in_rhp=False, projection='orth', use_arnoldi=False, conv_crit='sigma', compute_errors=False, irka_options=None)[source]

Reduce using SOR-IRKA.

It uses IRKA as the intermediate reductor, to reduce from 2r to r poles. See Section 5.3.2 in [W12].

Parameters

r
Order of the reduced order model.
sigma

Initial interpolation points (closed under conjugation).

If None, interpolation points are log-spaced between 0.1 and 10. If sigma is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a one-dimensional array-like of length r.

sigma and rd0 cannot both be not None.

b

Initial right tangential directions.

If None, if is chosen as all ones. If b is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a VectorArray of length r from d.B.source.

b and rd0 cannot both be not None.

c

Initial left tangential directions.

If None, if is chosen as all ones. If c is an int, it is used as a seed to generate it randomly. Otherwise, it needs to be a VectorArray of length r from d.Cp.range.

c and rd0 cannot both be not None.

rd0

Initial reduced order model.

If None, then sigma, b, and c are used. Otherwise, it needs to be an LTISystem of order r and it is used to construct sigma, b, and c.

tol
Tolerance for the convergence criterion.
maxit
Maximum number of iterations.
num_prev
Number of previous iterations to compare the current iteration to. Larger number can avoid occasional cyclic behavior of IRKA.
force_sigma_in_rhp
If False, new interpolation are reflections of the current reduced order model’s poles. Otherwise, only the poles in the left half-plane are reflected.
projection

Projection method:

  • 'orth': projection matrices are orthogonalized with respect to the Euclidean inner product
  • 'biorth': projection matrices are biorthogolized with respect to the E product
conv_crit

Convergence criterion:

  • 'sigma': relative change in interpolation points
  • 'h2': relative \mathcal{H}_2 distance of reduced-order models
compute_errors

Should the relative \mathcal{H}_2-errors of intermediate reduced order models be computed.

Warning

Computing \mathcal{H}_2-errors is expensive. Use this option only if necessary.

irka_options
Dict of options for IRKAReductor.reduce.

Returns

rd
Reduced LTISystem model.
pymor.tools package
Submodules
context module
class pymor.tools.context.NoContext[source]

Bases: object

counter module
class pymor.tools.counter.Counter(start=0)[source]

Bases: object

Methods

Counter inc
deprecated module
class pymor.tools.deprecated.Deprecated(alt='no alternative given')[source]

Bases: object

This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used.

__call__(func)[source]

Call self as a function.

__get__(obj, ownerClass=None)[source]

Return a wrapper that binds self as a method of obj (!)

floatcmp module
pymor.tools.floatcmp.float_cmp(x, y, rtol=1e-14, atol=1e-14)[source]

Compare x and y component-wise for almost equality.

For scalars we define almost equality as

float_cmp(x,y) <=> |x - y| <= atol + |y|*rtol

Note

Numpy’s allclose method uses the same definition but treats arrays containing infinities as close if the infinities are at the same places and all other entries are close. In our definition, arrays containing infinities can never be close which seems more appropriate in most cases.

Parameters

x, y
NumPy arrays to be compared. Have to be broadcastable to the same shape.
rtol
The relative tolerance.
atol
The absolute tolerance.

Defaults

rtol, atol (see pymor.core.defaults)


pymor.tools.floatcmp.float_cmp_all(x, y, rtol=None, atol=None)[source]

Compare x and y for almost equality.

Returns True if all components of x are almost equal to the corresponding components of y.

See float_cmp.

frozendict module
class pymor.tools.frozendict.FrozenDict(*args, **kwargs)[source]

Bases: dict

An immutable dictionary.

Methods

dict copy, fromkeys, get, items, keys, values, __contains__, __getitem__, __sizeof__

Attributes

FrozenDict clear, pop, popitem, setdefault, update
static __new__(cls, *args, **kwargs)[source]

Create and return a new object. See help(type) for accurate signature.

__reduce__()[source]

Helper for pickle.

__repr__()[source]

Return repr(self).

inplace module
inverse module
pymor.tools.inverse.inv_transposed_two_by_two(A)[source]

Efficiently compute the tranposed inverses of a NumPy array of 2x2-matrices

|  retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).

pymor.tools.inverse.inv_two_by_two(A)[source]

Efficiently compute the inverses of a NumPy array of 2x2-matrices

|  retval[i1,...,ik,m,n] = numpy.linalg.inv(A[i1,...,ik,:,:]).
io module
pymor.tools.io.SafeTemporaryFileName(name=None, parent_dir=None)[source]

Cross Platform safe equivalent of re-opening a NamedTemporaryFile Creates an automatically cleaned up temporary directory with a single file therein.

name: filename component, defaults to ‘temp_file’ dir: the parent dir of the new tmp dir. defaults to tempfile.gettempdir()


pymor.tools.io.load_matrix(path, key=None)[source]
mpi module

This module provides helper methods to use pyMOR in parallel with MPI.

Executing this module will run event_loop on all MPI ranks except for rank 0 where either a given script is executed:

mpirun -n 16 python -m pymor.tools.mpi /path/to/script

or an interactive session is started:

mpirun -n 16 python -m pymor.tools.mpi

When IPython is available, an IPython kernel is started which the user can connect to by calling:

ipython console --existing file_name_printed_by_ipython.json

(Starting the IPython console directly will not work properly with most MPI implementations.) When IPython is not available, the builtin Python REPL is started.

When event_loop is running on the MPI ranks, call can be used on rank 0 to execute the same Python function (given as first argument) simultaneously on all MPI ranks (including rank 0). Calling quit will exit event_loop on all MPI ranks.

Additionally, this module provides several helper methods which are intended to be used in conjunction with call: mpi_info will print a summary of all active MPI ranks, run_code will execute the given code string on all MPI ranks, import_module imports the module with the given path.

A simple object management is implemented with the manage_object, get_object and remove_object methods. It is the user’s responsibility to ensure that calls to manage_object are executed in the same order on all MPI ranks to ensure that the returned ObjectId refers to the same distributed object on all ranks. The functions function_call, function_call_manage, method_call, method_call_manage map instances ObjectId transparently to distributed objects. function_call_manage and method_call_manage will call manage_object on the return value and return the corresponding ObjectId. The functions method_call and method_call_manage are given an ObjectId and a string as first and second argument and execute the method named by the second argument on the object referred to by the first argument.


class pymor.tools.mpi.ObjectId[source]

Bases: int

A handle to an MPI distributed object.

Methods

int bit_length, conjugate, from_bytes, to_bytes, __ceil__, __floor__, __new__, __round__, __sizeof__, __trunc__

Attributes

int denominator, imag, numerator, real

pymor.tools.mpi.call(method, *args, **kwargs)[source]

Execute method on all MPI ranks.

Assuming event_loop is running on all MPI ranks (except rank 0), this will execute method on all ranks (including rank 0) with positional arguments args and keyword arguments kwargs.

Parameters

method
The function to execute on all ranks (must be picklable).
args
The positional arguments for method.
kwargs
The keyword arguments for method.

Returns

The return value of method on rank 0.


pymor.tools.mpi.event_loop()[source]

Launches an MPI-based event loop.

Events can be sent by either calling call on rank 0 to execute an arbitrary method on all ranks or by calling quit to exit the loop.


pymor.tools.mpi.event_loop_settings(auto_launch=True)[source]

Settings for pyMOR’s MPI event loop.

Parameters

auto_launch
If True, automatically execute event_loop on all MPI ranks (except 0) when pyMOR is imported.

Defaults

auto_launch (see pymor.core.defaults)


pymor.tools.mpi.function_call(f, *args, **kwargs)[source]

Execute the function f with given arguments.

Intended to be used in conjunction with call. Arguments of type ObjectId are transparently mapped to the object they refer to.


pymor.tools.mpi.function_call_manage(f, *args, **kwargs)[source]

Execute the function f and manage the return value.

Intended to be used in conjunction with call. The return value of f is managed by calling manage_object and the corresponding ObjectId is returned. Arguments of type ObjectId are transparently mapped to the object they refer to.


pymor.tools.mpi.get_object(obj_id)[source]

Return the object referred to by obj_id.


pymor.tools.mpi.import_module(path)[source]

Import the module named by path.

Intended to be used in conjunction with call.


pymor.tools.mpi.manage_object(obj)[source]

Keep track of obj and return an ObjectId handle.


pymor.tools.mpi.method_call(obj_id, name_, *args, **kwargs)[source]

Execute a method with given arguments.

Intended to be used in conjunction with call. Arguments of type ObjectId are transparently mapped to the object they refer to.

Parameters

obj_id
The ObjectId of the object on which to call the method.
name_
Name of the method to call.
args
Positional arguments for the method.
kwargs
Keyword arguments for the method.

pymor.tools.mpi.method_call_manage(obj_id, name_, *args, **kwargs)[source]

Execute a method with given arguments and manage the return value.

Intended to be used in conjunction with call. The return value of the called method is managed by calling manage_object and the corresponding ObjectId is returned. Arguments of type ObjectId are transparently mapped to the object they refer to.

Parameters

obj_id
The ObjectId of the object on which to call the method.
name_
Name of the method to call.
args
Positional arguments for the method.
kwargs
Keyword arguments for the method.

pymor.tools.mpi.mpi_info()[source]

Print some information on the MPI setup.

Intended to be used in conjunction with call.


pymor.tools.mpi.quit()[source]

Exit the event loop on all MPI ranks.

This will cause event_loop to terminate on all MPI ranks.


pymor.tools.mpi.remove_object(obj_id)[source]

Remove the object referred to by obj_id from the registry.


pymor.tools.mpi.run_code(code)[source]

Execute the code string code.

Intended to be used in conjunction with call.

pprint module
pymor.tools.pprint.format_array(array, compact_print=False)[source]

Creates a formatted string representation of a NumPy array.

Parameters

array
the NumPy array to be formatted
compact_print
If True, return a shorter version of string representation.

Returns

The string representation.

Defaults

compact_print (see pymor.core.defaults)

quadratures module
class pymor.tools.quadratures.GaussQuadratures[source]

Bases: object

Gauss quadrature on the interval [0, 1]

Attributes

GaussQuadratures a, order_map, orders, points, weights
classmethod iter_quadrature(order=None, npoints=None)[source]

iterates over a quadrature tuple wise

classmethod quadrature(order=None, npoints=None)[source]

returns tuple (P, W) where P is an array of Gauss points with corresponding weights W for the given integration order “order” or with “npoints” integration points

random module
pymor.tools.random.new_random_state(seed=42)[source]

Returns a new NumPy RandomState.

Parameters

seed
Seed to use for initializing the random state.

Returns

New RandomState object.

Defaults

seed (see pymor.core.defaults)

relations module
table module
pymor.tools.table.format_table(rows, width='AUTO', title=None)[source]
timing module
class pymor.tools.timing.Timer(section, log=<Logger pymor.tools.timing (INFO)>)[source]

Bases: object

You can use me as a context manager, plain instance or decorator to time execution of a code scope:

with Timer() as timer:
    do_some_stuff()
    do more stuff()
#outputs time in (s)

### OR ###

@timing.Timer('name', logging.debug)
def function(*args):
    do_stuff

function(1)
#outputs time in (s) to logging.debug

### OR ###

timer = timing.Timer()
timer.start()
do_stuff()
timer.stop()
print(timer.dt)

Methods

Timer start, stop
__call__(func)[source]

Call self as a function.


pymor.tools.timing.busywait(amount)[source]
vtkio module
pymor.tools.vtkio.write_vtk(grid, data, filename_base, codim=2, binary_vtk=True, last_step=None)[source]

Output grid-associated data in (legacy) vtk format

Parameters

grid
A Grid with triangular or rectilinear reference element.
data
VectorArray with either cell (ie one datapoint per codim 0 entity) or vertex (ie one datapoint per codim 2 entity) data in each array element.
codim
the codimension associated with the data
filename_base
common component for output files in timeseries
binary_vtk
if false, output files contain human readable inline ascii data, else appended binary
last_step
if set must be <= len(data) to restrict output of timeseries
pymor.vectorarrays package
Submodules
block module
class pymor.vectorarrays.block.BlockVectorArray(blocks, space)[source]

Bases: pymor.vectorarrays.interfaces.VectorArrayInterface

VectorArray where each vector is a direct sum of sub-vectors.

Given a list of equal length VectorArrays blocks, this VectorArray represents the direct sums of the vectors contained in the arrays. The associated VectorSpace is BlockVectorSpace.

BlockVectorArray can be used in conjunction with BlockOperator.

__delitem__(ind)[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__len__()[source]

The number of vectors in the array.

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
block(ind)[source]

Returns a copy of each block (no slicing).

conj()[source]

Complex conjugation.

copy(deep=False)[source]

Returns a copy of the array.

All VectorArray implementations in pyMOR have copy-on-write semantics: if not specified otherwise by setting deep to True, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.

Note that for NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.

Parameters

deep
Ensure that an actual copy of the array data is made (see above).

Returns

A copy of the VectorArray.

dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
imag

Imaginary part.

l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

lincomb(coefficients)[source]

Returns linear combinations of the vectors contained in the array.

Parameters

coefficients
A NumPy array of dimension 1 or 2 containing the linear coefficients. coefficients.shape[-1] has to agree with len(self).

Returns

A VectorArray result such that

result[i] = ∑ self[j] * coefficients[i,j]

in case coefficients is of dimension 2, otherwise len(result) == 1 and

result[0] = ∑ self[j] * coefficients[j].
pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).
real

Real part.

scal(alpha)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.
sup_norm()[source]

The l-infinity-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

to_numpy(ensure_copy=False)[source]

Return (len(self), self.dim) NumPy Array with the data stored in the array.

Parameters

ensure_copy
If False, modifying the returned NumPy array might alter the original VectorArray. If True always a copy of the array data is made.

class pymor.vectorarrays.block.BlockVectorArrayView(base, ind)[source]

Bases: pymor.vectorarrays.block.BlockVectorArray


class pymor.vectorarrays.block.BlockVectorSpace(subspaces, id_=None)[source]

Bases: pymor.vectorarrays.interfaces.VectorSpaceInterface

VectorSpace of BlockVectorArrays.

A BlockVectorSpace is defined by the VectorSpaces of the individual subblocks which constitute a given array. In particular for a given :class`BlockVectorArray` U, we have the identity

(U.blocks[0].space, U.blocks[1].space, ..., U.blocks[-1].space) == U.space.

Parameters

subspaces
The tuple defined above.
__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

from_numpy(data, ensure_copy=False)[source]

Create a VectorArray from a NumPy array

Note that this method will not be supported by all vector space implementations.

Parameters

data
NumPy array of shape (len, dim) where len is the number of vectors and dim their dimension.
ensure_copy
If False, modifying the returned VectorArray might alter the original NumPy array. If True always a copy of the array data is made.

Returns

A VectorArray with data as data.

zeros(count=1, reserve=0)[source]

Create a VectorArray of null vectors

Parameters

count
The number of vectors.
reserve
Hint for the backend to which length the array will grow.

Returns

A VectorArray containing count vectors with each component zero.

constructions module
pymor.vectorarrays.constructions.cat_arrays(vector_arrays)[source]

Return a new VectorArray which is a concatenation of the arrays in vector_arrays.

interfaces module
class pymor.vectorarrays.interfaces.VectorArrayInterface[source]

Bases: pymor.core.interfaces.BasicInterface

Interface for vector arrays.

A vector array should be thought of as a list of (possibly high-dimensional) vectors. While the vectors themselves will be inaccessible in general (e.g. because they are managed by an external PDE solver code), operations on the vectors like addition can be performed via this interface.

It is assumed that the number of vectors is small enough such that scalar data associated to each vector can be handled on the Python side. As such, methods like l2_norm or gramian will always return NumPy arrays.

An implementation of the VectorArrayInterface via NumPy arrays is given by NumpyVectorArray. In general, it is the implementors decision how memory is allocated internally (e.g. continuous block of memory vs. list of pointers to the individual vectors.) Thus, no general assumptions can be made on the costs of operations like appending to or removing vectors from the array. As a hint for ‘continuous block of memory’ implementations, zeros provides a reserve keyword argument which allows to specify to what size the array is assumed to grow.

As with NumPy array, VectorArrays can be indexed with numbers, slices and lists or one-dimensional NumPy arrays. Indexing will always return a new VectorArray which acts as a view into the original data. Thus, if the indexed array is modified via scal or axpy, the vectors in the original array will be changed. Indices may be negative, in which case the vector is selected by counting from the end of the array. Moreover indices can be repeated, in which case the corresponding vector is selected several times. The resulting view will be immutable, however.

Note

It is disallowed to append vectors to a VectorArray view or to remove vectors from it. Removing vectors from an array with existing views will lead to undefined behavior of these views. As such, it is generally advisable to make a copy of a view for long term storage. Since copy has copy-on-write semantics, this will usually cause little overhead.

dim

The dimension of the vectors in the array.

is_view

True if the array is a view obtained by indexing another array.

space

The VectorSpace the array belongs to.

__delitem__(ind)[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__len__()[source]

The number of vectors in the array.

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
check_ind(ind)[source]

Check if ind is an admissible list of indices in the sense of the class documentation.

check_ind_unique(ind)[source]

Check if ind is an admissible list of non-repeated indices in the sense of the class documentation.

conj()[source]

Complex conjugation.

copy(deep=False)[source]

Returns a copy of the array.

All VectorArray implementations in pyMOR have copy-on-write semantics: if not specified otherwise by setting deep to True, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.

Note that for NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.

Parameters

deep
Ensure that an actual copy of the array data is made (see above).

Returns

A copy of the VectorArray.

dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
empty(reserve=0)[source]

Create an empty VectorArray of the same VectorSpace.

This is a shorthand for self.space.zeros(0, reserve).

Parameters

reserve
Hint for the backend to which length the array will grow.

Returns

An empty VectorArray.

gramian(product=None)[source]

Shorthand for self.inner(self, product).

imag()[source]

Imaginary part.

inner(other, product=None)[source]

Inner products w.r.t. given product Operator.

Equivalent to self.dot(other) if product is None, else equivalent to product.apply2(self, other).

l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

len_ind(ind)[source]

Return the number of given indices.

len_ind_unique(ind)[source]

Return the number of specified unique indices.

lincomb(coefficients)[source]

Returns linear combinations of the vectors contained in the array.

Parameters

coefficients
A NumPy array of dimension 1 or 2 containing the linear coefficients. coefficients.shape[-1] has to agree with len(self).

Returns

A VectorArray result such that

result[i] = ∑ self[j] * coefficients[i,j]

in case coefficients is of dimension 2, otherwise len(result) == 1 and

result[0] = ∑ self[j] * coefficients[j].
norm(product=None)[source]

Norm w.r.t. given inner product Operator.

Equivalent to self.l2_norm() if product is None, else equivalent to np.sqrt(product.pairwise_apply2(self, self)).

norm2(product=None)[source]

Squared norm w.r.t. given inner product Operator.

Equivalent to self.l2_norm2() if product is None, else equivalent to product.pairwise_apply2(self, self).

normalize_ind(ind)[source]

Normalize given indices such that they are independent of the array length.

pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).
pairwise_inner(other, product=None)[source]

Pairwise inner products w.r.t. given product Operator.

Equivalent to self.pairwise_dot(other) if product is None, else equivalent to product.pairwise_apply2(self, other).

real()[source]

Real part.

scal(alpha)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.
sub_index(ind, ind_ind)[source]

Return indices corresponding to the view self[ind][ind_ind]

sup_norm()[source]

The l-infinity-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

to_numpy(ensure_copy=False)[source]

Return (len(self), self.dim) NumPy Array with the data stored in the array.

Parameters

ensure_copy
If False, modifying the returned NumPy array might alter the original VectorArray. If True always a copy of the array data is made.
zeros(count=1, reserve=0)[source]

Create a VectorArray of null vectors of the same VectorSpace.

This is a shorthand for self.space.zeros(count, reserve).

Parameters

count
The number of vectors.
reserve
Hint for the backend to which length the array will grow.

Returns

A VectorArray containing count vectors with each component zero.


class pymor.vectorarrays.interfaces.VectorSpaceInterface[source]

Bases: pymor.core.interfaces.ImmutableInterface

Class describing a vector space.

Vector spaces act as factories for VectorArrays of vectors contained in them. As such, they hold all data necessary to create VectorArrays of a given type (e.g. the dimension of the vectors, or a socket for communication with an external PDE solver).

New VectorArrays of null vectors are created via zeros. The make_array method builds a new VectorArray from given raw data of the underlying linear algebra backend (e.g. a NumPy array in the case of NumpyVectorSpace). Some vector spaces can create new VectorArrays from a given NumPy array via the from_numpy method.

Each vector space has a string id to distinguish mathematically different spaces appearing in the formulation of a given problem.

Vector spaces can be compared for equality via the == and != operators. To test if a given VectorArray is an element of the space, the in operator can be used.

id

None, or a string describing the mathematical identity of the vector space (for instance to distinguish different components in an equation system).

dim

The dimension (number of degrees of freedom) of the vectors contained in the space.

is_scalar

Equivalent to isinstance(space, NumpyVectorSpace) and space.dim == 1.

__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

__ne__(other)[source]

Return self!=value.

__repr__()[source]

Return repr(self).

empty(reserve=0)[source]

Create an empty VectorArray

This is a shorthand for self.zeros(0, reserve).

Parameters

reserve
Hint for the backend to which length the array will grow.

Returns

An empty VectorArray.

from_numpy(data, ensure_copy=False)[source]

Create a VectorArray from a NumPy array

Note that this method will not be supported by all vector space implementations.

Parameters

data
NumPy array of shape (len, dim) where len is the number of vectors and dim their dimension.
ensure_copy
If False, modifying the returned VectorArray might alter the original NumPy array. If True always a copy of the array data is made.

Returns

A VectorArray with data as data.

make_array(**kwargs)[source]

Create a VectorArray from raw data.

This method is used in the implementation of Operators and Discretizations to create new VectorArrays from raw data of the underlying solver backends. The ownership of the data is transferred to the newly created array.

The exact signature of this method depends on the wrapped solver backend.

zeros(count=1, reserve=0)[source]

Create a VectorArray of null vectors

Parameters

count
The number of vectors.
reserve
Hint for the backend to which length the array will grow.

Returns

A VectorArray containing count vectors with each component zero.

list module
class pymor.vectorarrays.list.CopyOnWriteVector[source]

Bases: pymor.vectorarrays.list.VectorInterface

Methods

CopyOnWriteVector axpy, copy, from_instance, scal
VectorInterface amax, dofs, dot, l1_norm, l2_norm, l2_norm2, sup_norm
BasicInterface disable_logging, enable_logging, has_interface_name, implementor_names, implementors

class pymor.vectorarrays.list.ListVectorArray(vectors, space)[source]

Bases: pymor.vectorarrays.interfaces.VectorArrayInterface

VectorArray implemented as a Python list of vectors.

This VectorArray implementation is the first choice when creating pyMOR wrappers for external solvers which are based on single vector objects. In order to do so, a wrapping subclass of VectorInterface has to be provided on which the implementation of ListVectorArray will operate. The associated VectorSpace is a subclass of ListVectorSpace.

For an example, see NumpyVector, NumpyListVectorSpace or FenicsVector, FenicsVectorSpace.

__delitem__(ind)[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__len__()[source]

The number of vectors in the array.

__str__()[source]

Return str(self).

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
copy(deep=False)[source]

Returns a copy of the array.

All VectorArray implementations in pyMOR have copy-on-write semantics: if not specified otherwise by setting deep to True, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.

Note that for NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.

Parameters

deep
Ensure that an actual copy of the array data is made (see above).

Returns

A copy of the VectorArray.

dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
gramian(product=None)[source]

Shorthand for self.inner(self, product).

l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

lincomb(coefficients)[source]

Returns linear combinations of the vectors contained in the array.

Parameters

coefficients
A NumPy array of dimension 1 or 2 containing the linear coefficients. coefficients.shape[-1] has to agree with len(self).

Returns

A VectorArray result such that

result[i] = ∑ self[j] * coefficients[i,j]

in case coefficients is of dimension 2, otherwise len(result) == 1 and

result[0] = ∑ self[j] * coefficients[j].
pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).
scal(alpha)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.
sup_norm()[source]

The l-infinity-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

to_numpy(ensure_copy=False)[source]

Return (len(self), self.dim) NumPy Array with the data stored in the array.

Parameters

ensure_copy
If False, modifying the returned NumPy array might alter the original VectorArray. If True always a copy of the array data is made.

class pymor.vectorarrays.list.ListVectorArrayNumpyView(array)[source]

Bases: object

__repr__()[source]

Return repr(self).


class pymor.vectorarrays.list.ListVectorArrayView(base, ind)[source]

Bases: pymor.vectorarrays.list.ListVectorArray

__delitem__(ind)[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__str__()[source]

Return str(self).

append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
scal(alpha)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.

class pymor.vectorarrays.list.ListVectorSpace[source]

Bases: pymor.vectorarrays.interfaces.VectorSpaceInterface

VectorSpace of ListVectorArrays.

zeros(count=1, reserve=0)[source]

Create a VectorArray of null vectors

Parameters

count
The number of vectors.
reserve
Hint for the backend to which length the array will grow.

Returns

A VectorArray containing count vectors with each component zero.


class pymor.vectorarrays.list.NumpyListVectorSpace(dim, id_=None)[source]

Bases: pymor.vectorarrays.list.ListVectorSpace

__eq__(other)[source]

Return self==value.


class pymor.vectorarrays.list.NumpyVector(array)[source]

Bases: pymor.vectorarrays.list.CopyOnWriteVector

Vector stored in a NumPy 1D-array.

Methods

NumpyVector amax, dofs, dot, from_instance, l1_norm, l2_norm, l2_norm2, to_numpy
CopyOnWriteVector axpy, copy, scal
VectorInterface sup_norm
BasicInterface disable_logging, enable_logging, has_interface_name, implementor_names, implementors

class pymor.vectorarrays.list.VectorInterface[source]

Bases: pymor.core.interfaces.BasicInterface

Interface for vectors used in conjunction with ListVectorArray.

This interface must be satisfied by the individual entries of the vector list managed by ListVectorArray. All interface methods have a direct counterpart in the VectorArray interface.

Methods

VectorInterface amax, axpy, copy, dofs, dot, l1_norm, l2_norm, l2_norm2, scal, sup_norm
BasicInterface disable_logging, enable_logging, has_interface_name, implementor_names, implementors
mpi module

Wrapper classes for building MPI distributed VectorArrays.

This module contains several wrapper classes which allow to transform single rank VectorArrays into MPI distributed VectorArrays which can be used on rank 0 like ordinary VectorArrays.

The implementations are based on the event loop provided by pymor.tools.mpi.


class pymor.vectorarrays.mpi.MPIVectorArray(obj_id, space)[source]

Bases: pymor.vectorarrays.interfaces.VectorArrayInterface

MPI distributed VectorArray.

Given a local VectorArray on each MPI rank, this wrapper class uses the event loop from pymor.tools.mpi to build a global MPI distributed vector array from these local arrays.

Instances of MPIVectorArray can be used on rank 0 like any other (non-distributed) VectorArray.

Note, however, that the implementation of the local VectorArrays needs to be MPI aware. For instance, cls.dot must perform the needed MPI communication to sum up the local inner products and return the sums on rank 0.

Default implementations for all communication requiring interface methods are provided by MPIVectorArrayAutoComm (also see MPIVectorArrayNoComm).

Note that resource cleanup is handled by object.__del__. Please be aware of the peculiarities of destructors in Python!

The associated VectorSpace is MPIVectorSpace.

__delitem__(ind)[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__len__()[source]

The number of vectors in the array.

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
copy(deep=False)[source]

Returns a copy of the array.

All VectorArray implementations in pyMOR have copy-on-write semantics: if not specified otherwise by setting deep to True, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.

Note that for NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.

Parameters

deep
Ensure that an actual copy of the array data is made (see above).

Returns

A copy of the VectorArray.

dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

lincomb(coefficients)[source]

Returns linear combinations of the vectors contained in the array.

Parameters

coefficients
A NumPy array of dimension 1 or 2 containing the linear coefficients. coefficients.shape[-1] has to agree with len(self).

Returns

A VectorArray result such that

result[i] = ∑ self[j] * coefficients[i,j]

in case coefficients is of dimension 2, otherwise len(result) == 1 and

result[0] = ∑ self[j] * coefficients[j].
pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).
scal(alpha)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.

class pymor.vectorarrays.mpi.MPIVectorArrayAutoComm(obj_id, space)[source]

Bases: pymor.vectorarrays.mpi.MPIVectorArray

MPI distributed VectorArray.

This is a subclass of MPIVectorArray which provides default implementations for all communication requiring interface methods for the case when the wrapped array is not MPI aware.

Note, however, that depending on the discretization these default implementations might lead to wrong results (for instance in the presence of shared DOFs).

The associated VectorSpace is MPIVectorSpaceAutoComm.

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).

class pymor.vectorarrays.mpi.MPIVectorArrayNoComm(obj_id, space)[source]

Bases: pymor.vectorarrays.mpi.MPIVectorArray

MPI distributed VectorArray.

This is a subclass of MPIVectorArray which overrides all communication requiring interface methods to raise NotImplementedError.

This is mainly useful as a security measure when wrapping arrays for which simply calling the respective method on the wrapped arrays would lead to wrong results and MPIVectorArrayAutoComm cannot be used either (for instance in the presence of shared DOFs).

The associated VectorSpace is MPIVectorSpaceNoComm.

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).

class pymor.vectorarrays.mpi.MPIVectorSpace(local_spaces)[source]

Bases: pymor.vectorarrays.interfaces.VectorSpaceInterface

VectorSpace of MPIVectorArrays.

Parameters

local_spaces
tuple of the different VectorSpaces of the local VectorArrays on the MPI ranks. Alternatively, the length of local_spaces may be 1, in which case the same VectorSpace is assumed for all ranks.
__eq__(other)[source]

Return self==value.

__repr__()[source]

Return repr(self).

array_type

alias of MPIVectorArray

make_array(obj_id)[source]

Create array from rank-local VectorArray instances.

Parameters

obj_id
ObjectId of the MPI distributed instances of cls wrapped by this array.

Returns

The newly created : class:MPIVectorArray.

zeros(count=1, reserve=0)[source]

Create a VectorArray of null vectors

Parameters

count
The number of vectors.
reserve
Hint for the backend to which length the array will grow.

Returns

A VectorArray containing count vectors with each component zero.


class pymor.vectorarrays.mpi.MPIVectorSpaceAutoComm(local_spaces)[source]

Bases: pymor.vectorarrays.mpi.MPIVectorSpace

VectorSpace for MPIVectorArrayAutoComm.

array_type

alias of MPIVectorArrayAutoComm


class pymor.vectorarrays.mpi.MPIVectorSpaceNoComm(local_spaces)[source]

Bases: pymor.vectorarrays.mpi.MPIVectorSpace

VectorSpace for MPIVectorArrayNoComm.

array_type

alias of MPIVectorArrayNoComm


class pymor.vectorarrays.mpi.RegisteredLocalSpace[source]

Bases: int

Methods

int bit_length, conjugate, from_bytes, to_bytes, __ceil__, __floor__, __new__, __round__, __sizeof__, __trunc__

Attributes

int denominator, imag, numerator, real
__repr__()[source]

Return repr(self).

numpy module
class pymor.vectorarrays.numpy.NumpyVectorArray(array, space)[source]

Bases: pymor.vectorarrays.interfaces.VectorArrayInterface

VectorArray implementation via NumPy arrays.

This is the default VectorArray type used by all Operators in pyMOR’s discretization toolkit. Moreover, all reduced Operators are based on NumpyVectorArray.

This class is just a thin wrapper around the underlying NumPy array. Thus, while operations like axpy or dot will be quite efficient, removing or appending vectors will be costly.

The associated VectorSpace is NumpyVectorSpace.

__delitem__(ind)[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__len__()[source]

The number of vectors in the array.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

amax(*, _ind=None)[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x, *, _ind=None)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
conj()[source]

Complex conjugation.

copy(deep=False, *, _ind=None)[source]

Returns a copy of the array.

All VectorArray implementations in pyMOR have copy-on-write semantics: if not specified otherwise by setting deep to True, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.

Note that for NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.

Parameters

deep
Ensure that an actual copy of the array data is made (see above).

Returns

A copy of the VectorArray.

dofs(dof_indices, *, _ind=None)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other, *, _ind=None)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
imag

Imaginary part.

l1_norm(*, _ind=None)[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm(*, _ind=None)[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2(*, _ind=None)[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

lincomb(coefficients, *, _ind=None)[source]

Returns linear combinations of the vectors contained in the array.

Parameters

coefficients
A NumPy array of dimension 1 or 2 containing the linear coefficients. coefficients.shape[-1] has to agree with len(self).

Returns

A VectorArray result such that

result[i] = ∑ self[j] * coefficients[i,j]

in case coefficients is of dimension 2, otherwise len(result) == 1 and

result[0] = ∑ self[j] * coefficients[j].
pairwise_dot(other, *, _ind=None)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).
real

Real part.

scal(alpha, *, _ind=None)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.
sup_norm(*, _ind=None)[source]

The l-infinity-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

to_numpy(ensure_copy=False)[source]

Return (len(self), self.dim) NumPy Array with the data stored in the array.

Parameters

ensure_copy
If False, modifying the returned NumPy array might alter the original VectorArray. If True always a copy of the array data is made.

class pymor.vectorarrays.numpy.NumpyVectorArrayView(array, ind)[source]

Bases: pymor.vectorarrays.numpy.NumpyVectorArray

__delitem__()[source]

Remove vectors from the array.

__getitem__(ind)[source]

Return a VectorArray view onto a subset of the vectors in the array.

__len__()[source]

The number of vectors in the array.

__repr__()[source]

Return repr(self).

amax()[source]

The maximum absolute value of the DOFs contained in the array.

Returns

max_ind
NumPy array containing for each vector a DOF index at which the maximum is attained.
max_val
NumPy array containing for each vector the maximum absolute value of its DOFs.
append(other, remove_from_other=False)[source]

Append vectors to the array.

Parameters

other
A VectorArray containing the vectors to be appended.
remove_from_other
If True, the appended vectors are removed from other. For list-like implementations this can be used to prevent unnecessary copies of the involved vectors.
axpy(alpha, x)[source]

BLAS AXPY operation.

This method forms the sum

self = alpha*x + self

If the length of x is 1, the same x vector is used for all vectors in self. Otherwise, the lengths of self and x have to agree. If alpha is a scalar, each x vector is multiplied with the same factor alpha. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the coefficients for each x vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in x are multiplied.
x
A VectorArray containing the x-summands.
copy(deep=False)[source]

Returns a copy of the array.

All VectorArray implementations in pyMOR have copy-on-write semantics: if not specified otherwise by setting deep to True, the returned copy will hold a handle to the same array data as the original array, and a deep copy of the data will only be performed when one of the arrays is modified.

Note that for NumpyVectorArray, a deep copy is always performed when only some vectors in the array are copied.

Parameters

deep
Ensure that an actual copy of the array data is made (see above).

Returns

A copy of the VectorArray.

dofs(dof_indices)[source]

Extract DOFs of the vectors contained in the array.

Parameters

dof_indices
List or 1D NumPy array of indices of the DOFs that are to be returned.

Returns

A NumPy array result such that result[i, j] is the dof_indices[j]-th DOF of the i-th vector of the array.

dot(other)[source]

Returns the inner products between VectorArray elements.

In the case of complex numbers, this is antilinear in the first argument, i.e. in ‘self’. Complex conjugation is done in the first argument because most numerical software in the community handles it this way: Numpy, DUNE, FEniCS, Eigen, Matlab and BLAS do complex conjugation in the first argument, only PetSc and deal.ii do complex conjugation in the second argument.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i, j] = ( self[i], other[j] ).
l1_norm()[source]

The l1-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm()[source]

The l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

l2_norm2()[source]

The squared l2-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

lincomb(coefficients)[source]

Returns linear combinations of the vectors contained in the array.

Parameters

coefficients
A NumPy array of dimension 1 or 2 containing the linear coefficients. coefficients.shape[-1] has to agree with len(self).

Returns

A VectorArray result such that

result[i] = ∑ self[j] * coefficients[i,j]

in case coefficients is of dimension 2, otherwise len(result) == 1 and

result[0] = ∑ self[j] * coefficients[j].
pairwise_dot(other)[source]

Returns the pairwise inner products between VectorArray elements.

Parameters

other
A VectorArray containing the second factors.

Returns

A NumPy array result such that

result[i] = ( self[i], other[i] ).
scal(alpha)[source]

BLAS SCAL operation (in-place scalar multiplication).

This method calculates

self = alpha*self

If alpha is a scalar, each vector is multiplied by this scalar. Otherwise, alpha has to be a one-dimensional NumPy array of the same length as self containing the factors for each vector.

Parameters

alpha
The scalar coefficient or one-dimensional NumPy array of coefficients with which the vectors in self are multiplied.
sup_norm()[source]

The l-infinity-norms of the vectors contained in the array.

Returns

A NumPy array result such that result[i] contains the norm of self[i].

to_numpy(ensure_copy=False)[source]

Return (len(self), self.dim) NumPy Array with the data stored in the array.

Parameters

ensure_copy
If False, modifying the returned NumPy array might alter the original VectorArray. If True always a copy of the array data is made.

class pymor.vectorarrays.numpy.NumpyVectorSpace(dim, id_=None)[source]

Bases: pymor.vectorarrays.interfaces.VectorSpaceInterface

VectorSpace of NumpyVectorArrays.

Parameters

dim
The dimension of the vectors contained in the space.
id
See id.
__eq__(other)[source]

Return self==value.

__hash__()[source]

Return hash(self).

__repr__()[source]

Return repr(self).

is_scalar

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

zeros(count=1, reserve=0)[source]

Create a VectorArray of null vectors

Parameters

count
The number of vectors.
reserve
Hint for the backend to which length the array will grow.

Returns

A VectorArray containing count vectors with each component zero.

Submodules

basic module

This module imports some commonly used methods and classes.

You can use from pymor.basic import * in interactive session to have the most important parts of pyMOR directly available.

version module

pymor.version.get_versions()[source]

Demo Applications

pymordemos package

Submodules

analyze_pickle module

Analyze pickled data demo.

Usage:
analyze_pickle.py histogram [–detailed=DETAILED_DATA] [–error-norm=NORM] REDUCED_DATA SAMPLES analyze_pickle.py convergence [–detailed=DETAILED_DATA] [–error-norm=NORM] [–ndim=NDIM] REDUCED_DATA SAMPLES analyze_pickle.py (-h | –help)

This demo loads a pickled reduced discretization, solves for random parameters, estimates the reduction errors and then visualizes these estimates. If the detailed discretization and the reductor are also provided, the estimated error is visualized in comparison to the real reduction error.

The needed data files are created by the thermal block demo, by setting the ‘–pickle’ option.

Arguments:

REDUCED_DATA File containing the pickled reduced discretization.

SAMPLES Number of parameter samples to test with.

Options:
--detailed=DETAILED_DATA
 File containing the high-dimensional discretization and the reductor.
--error-norm=NORM
 Name of norm in which to compute the errors.
--ndim=NDIM Number of reduced basis dimensions for which to estimate the error.

pymordemos.analyze_pickle._bins(start, stop, steps=100)[source]

numpy has a quirk in unreleased master where logspace might sometimes not return a 1d array


pymordemos.analyze_pickle.analyze_pickle_convergence(args)[source]

pymordemos.analyze_pickle.analyze_pickle_demo(args)[source]

pymordemos.analyze_pickle.analyze_pickle_histogram(args)[source]
burgers module

Burgers demo.

Solves a two-dimensional Burgers-type equation. See pymor.analyticalproblems.burgers for more details.

Usage:
burgers.py [-h] [–grid=NI] [–grid-type=TYPE] [–initial-data=TYPE] [–lxf-lambda=VALUE] [–nt=COUNT]
[–not-periodic] [–num-flux=FLUX] [–vx=XSPEED] [–vy=YSPEED] EXP
Arguments:
EXP Exponent
Options:
--grid=NI Use grid with (2*NI)*NI elements [default: 60].
--grid-type=TYPE
 Type of grid to use (rect, tria) [default: rect].
--initial-data=TYPE
 Select the initial data (sin, bump) [default: sin]
--lxf-lambda=VALUE
 Parameter lambda in Lax-Friedrichs flux [default: 1].
--nt=COUNT Number of time steps [default: 100].
--not-periodic Solve with dirichlet boundary conditions on left and bottom boundary.
--num-flux=FLUX
 Numerical flux to use (lax_friedrichs, engquist_osher) [default: engquist_osher].
-h, --help Show this message.
--vx=XSPEED Speed in x-direction [default: 1].
--vy=YSPEED Speed in y-direction [default: 1].

pymordemos.burgers.burgers_demo(args)[source]
burgers_ei module

Burgers with EI demo.

Model order reduction of a two-dimensional Burgers-type equation (see pymor.analyticalproblems.burgers) using the reduced basis method with empirical operator interpolation.

Usage:
burgers_ei.py [options] EXP_MIN EXP_MAX EI_SNAPSHOTS EISIZE SNAPSHOTS RBSIZE
Arguments:

EXP_MIN Minimal exponent

EXP_MAX Maximal exponent

EI_SNAPSHOTS Number of snapshots for empirical interpolation.

EISIZE Number of interpolation DOFs.

SNAPSHOTS Number of snapshots for basis generation.

RBSIZE Size of the reduced basis

Options:
--cache-region=REGION
 Name of cache region to use for caching solution snapshots (NONE, MEMORY, DISK, PERSISTENT) [default: DISK]
--ei-alg=ALG Interpolation algorithm to use (EI_GREEDY, DEIM) [default: EI_GREEDY].
--grid=NI Use grid with (2*NI)*NI elements [default: 60].
--grid-type=TYPE
 Type of grid to use (rect, tria) [default: rect].
--initial-data=TYPE
 Select the initial data (sin, bump) [default: sin]
--lxf-lambda=VALUE
 Parameter lambda in Lax-Friedrichs flux [default: 1].
--not-periodic Solve with dirichlet boundary conditions on left and bottom boundary.
--nt=COUNT Number of time steps [default: 100].
--num-flux=FLUX
 Numerical flux to use (lax_friedrichs, engquist_osher) [default: engquist_osher].
-h, --help Show this message.
-p, --plot-err Plot error.
--plot-ei-err Plot empirical interpolation error.
--plot-error-landscape
 Calculate and show plot of reduction error vs. basis sizes.
--plot-error-landscape-N=COUNT
 Number of basis sizes to test [default: 10]
--plot-error-landscape-M=COUNT
 Number of collateral basis sizes to test [default: 10]
--plot-solutions
 Plot some example solutions.
--test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10].
--vx=XSPEED Speed in x-direction [default: 1].
--vy=YSPEED Speed in y-direction [default: 1].
--ipython-engines=COUNT
 If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0]
--ipython-profile=PROFILE
 IPython profile to use for parallelization.

pymordemos.burgers_ei.main(args)[source]
delay module

Delay demo

Cascade of delay and integrator

elliptic module

Simple demonstration of solving the Poisson equation in 2D using pyMOR’s builtin discretizations.

Usage:
elliptic.py [–fv] [–rect] PROBLEM-NUMBER DIRICHLET-NUMBER NEUMANN-NUMBER NEUMANN-COUNT
Arguments:

PROBLEM-NUMBER {0,1}, selects the problem to solve

DIRICHLET-NUMBER {0,1,2}, selects the Dirichlet data function

NEUMANN-NUMBER {0,1}, selects the Neumann data function

NEUMANN-COUNT 0: no neumann boundary
1: right edge is neumann boundary 2: right+top edges are neumann boundary 3: right+top+bottom edges are neumann boundary
Options:
-h, --help Show this message.
--fv Use finite volume discretization instead of finite elements.
--rect Use RectGrid instead of TriaGrid.

pymordemos.elliptic.elliptic_demo(args)[source]
elliptic2 module

Simple demonstration of solving the Poisson equation in 2D using pyMOR’s builtin discretizations.

Usage:
elliptic2.py [–fv] PROBLEM-NUMBER N
Arguments:

PROBLEM-NUMBER {0,1}, selects the problem to solve

N Triangle count per direction

Options:
-h, --help Show this message.
--fv Use finite volume discretization instead of finite elements.

pymordemos.elliptic2.elliptic2_demo(args)[source]
elliptic_oned module

Proof of concept for solving the Poisson equation in 1D using linear finite elements and our grid interface

Usage:
elliptic_oned.py [–fv] PROBLEM-NUMBER N
Arguments:

PROBLEM-NUMBER {0,1}, selects the problem to solve

N Grid interval count

Options:
-h, --help Show this message.
--fv Use finite volume discretization instead of finite elements.

pymordemos.elliptic_oned.elliptic_oned_demo(args)[source]
elliptic_unstructured module

Simple demonstration of solving the Poisson equation in 2D on a circular sector domain of radius 1 using an unstructured mesh.

Note that Gmsh (http://geuz.org/gmsh/) is required for meshing.

Usage:
elliptic_unstructured.py ANGLE NUM_POINTS CLSCALE
Arguments:

ANGLE The angle of the circular sector.

NUM_POINTS The number of points that form the arc of the circular sector.

CLSCALE Mesh element size scaling factor.

Options:
-h, --help Show this message.

pymordemos.elliptic_unstructured.elliptic_gmsh_demo(args)[source]
hapod module

HAPOD demo.

Demonstrates compression of snapshot data with the HAPOD algorithm from [HLR18].

Usage:
hapod.py [options] TOL DIST INC
Arguments:
TOL Prescribed mean l2 approximation error. DIST Number of slices for distributed HAPOD. INC Number of steps for incremental HAPOD.
Options:
--grid=NI Use grid with (2*NI)*NI elements [default: 60].
-h, --help Show this message.
--nt=COUNT Number of time steps [default: 100].
--omega=OMEGA Parameter omega from HAPOD algorithm [default: 0.9].
--procs=PROCS Number of processes to use for parallelization [default: 0].
--snap=SNAP Number of snapshot trajectories to compute [default: 20].
--threads=THREADS
 Number of threads to use for parallelization [default: 0].

pymordemos.hapod.hapod_demo(args)[source]
heat module

2D heat equation demo

Discretization of the PDE:

\begin{align*}
    \partial_t z(x, y, t) &= \Delta z(x, y, t),      & 0 < x, y < 1,\ t > 0 \\
    -\nabla z(0, y, t) \cdot n &= z(0, y, t) - u(t), & 0 < y < 1, t > 0 \\
    -\nabla z(1, y, t) \cdot n &= z(1, y, t),        & 0 < y < 1, t > 0 \\
    -\nabla z(0, x, t) \cdot n &= z(0, x, t),        & 0 < x < 1, t > 0 \\
    -\nabla z(1, x, t) \cdot n &= z(1, x, t),        & 0 < x < 1, t > 0 \\
    z(x, y, 0) &= 0                                  & 0 < x, y < 1 \\
    y(t) &= \int_0^1 z(1, y, t) dy,                  & t > 0 \\
\end{align*}

where u(t) is the input and y(t) is the output.


pymordemos.heat.compute_hinf_norm(message, sys)[source]
parabolic module

Simple demonstration of solving parabolic equations using pyMOR’s builtin discretization toolkit.

Usage:
parabolic.py [options] heat TOP parabolic.py [options] dar SPEED
Arguments:
TOP The heat diffusion coefficient for the top bars. SPEED The advection speed.
Options:
-h, --help Show this message.
--fv Use finite volume discretization instead of finite elements.
--rect Use RectGrid instead of TriaGrid.
--grid=NI Use grid with NIxNI intervals [default: 100].
--nt=COUNT Number of time steps [default: 100].

pymordemos.parabolic.parabolic_demo(args)[source]
parabolic_mor module

Reduced basis approximation of the heat equation.

Usage:
parabolic_mor.py BACKEND ALG SNAPSHOTS RBSIZE TEST
Arguments:

BACKEND Discretization toolkit to use (pymor, fenics).

ALG The model reduction algorithm to use
(greedy, adaptive_greedy, pod).
SNAPSHOTS greedy/pod: number of training set parameters
adaptive_greedy: size of validation set.

RBSIZE Size of the reduced basis.

TEST Number of test parameters for reduction error estimation.


pymordemos.parabolic_mor.discretize_fenics()[source]

pymordemos.parabolic_mor.discretize_pymor()[source]

pymordemos.parabolic_mor.main(BACKEND, ALG, SNAPSHOTS, RBSIZE, TEST)[source]

pymordemos.parabolic_mor.reduce_adaptive_greedy(d, reductor, validation_mus, basis_size)[source]

pymordemos.parabolic_mor.reduce_greedy(d, reductor, snapshots, basis_size)[source]

pymordemos.parabolic_mor.reduce_pod(d, reductor, snapshots, basis_size)[source]
string_equation module

String equation example


pymordemos.string_equation.compute_hinf_norm(message, sys)[source]
thermalblock module

Thermalblock demo.

Usage:
thermalblock.py [options] XBLOCKS YBLOCKS SNAPSHOTS RBSIZE thermalblock.py -h | –help
Arguments:

XBLOCKS Number of blocks in x direction.

YBLOCKS Number of blocks in y direction.

SNAPSHOTS naive: ignored

greedy/pod: Number of training_set parameters per block
(in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).

adaptive_greedy: size of validation set.

RBSIZE Size of the reduced basis

Options:
--adaptive-greedy-rho=RHO
 See pymor.algorithms.adaptivegreedy [default: 1.1].
--adaptive-greedy-gamma=GAMMA
 See pymor.algorithms.adaptivegreedy [default: 0.2].
--adaptive-greedy-theta=THETA
 See pymor.algorithms.adaptivegreedy [default: 0.]
--alg=ALG The model reduction algorithm to use (naive, greedy, adaptive_greedy, pod) [default: greedy].
--cache-region=REGION
 Name of cache region to use for caching solution snapshots (none, memory, disk, persistent) [default: none].
--extension-alg=ALG
 Basis extension algorithm (trivial, gram_schmidt) to be used [default: gram_schmidt].
--fenics Use FEniCS discretization.
--grid=NI Use grid with 4*NI*NI elements [default: 100].
-h, --help Show this message.
--ipython-engines=COUNT
 If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0]
--ipython-profile=PROFILE
 IPython profile to use for parallelization.
--list-vector-array
 Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray.
--order=ORDER Polynomial order of the Lagrange finite elements to use in FEniCS discretization [default: 1].
--pickle=PREFIX
 Pickle reduced discretizaion, as well as reductor and high-dimensional discretization to files with this prefix.
--plot-err Plot error.
--plot-solutions
 Plot some example solutions.
--plot-error-sequence
 Plot reduction error vs. basis size.
--product=PROD Product (euclidean, h1) w.r.t. which to orthonormalize and calculate Riesz representatives [default: h1].
--reductor=RED Reductor (error estimator) to choose (traditional, residual_basis) [default: residual_basis]
--test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10].
--greedy-without-estimator
 Do not use error estimator for basis generation.

pymordemos.thermalblock.discretize_fenics(xblocks, yblocks, grid_num_intervals, element_order)[source]

pymordemos.thermalblock.discretize_pymor(xblocks, yblocks, grid_num_intervals, use_list_vector_array)[source]

pymordemos.thermalblock.main(args)[source]

pymordemos.thermalblock.parse_arguments(args)[source]

pymordemos.thermalblock.reduce_adaptive_greedy(d, reductor, validation_mus, extension_alg_name, max_extensions, use_estimator, rho, gamma, theta, pool)[source]

pymordemos.thermalblock.reduce_greedy(d, reductor, snapshots_per_block, extension_alg_name, max_extensions, use_estimator, pool)[source]

pymordemos.thermalblock.reduce_naive(d, reductor, basis_size)[source]

pymordemos.thermalblock.reduce_pod(d, reductor, snapshots_per_block, basis_size)[source]
thermalblock_adaptive module

Modified thermalblock demo using adaptive greedy basis generation algorithm.

Usage:
thermalblock_adaptive.py [options] RBSIZE thermalblock_adaptive.py -h | –help
Arguments:
RBSIZE Size of the reduced basis
Options:
-h, --help Show this message.
--without-estimator
 Do not use error estimator for basis generation.
--extension-alg=ALG
 Basis extension algorithm (trivial, gram_schmidt) to be used [default: gram_schmidt].
--grid=NI Use grid with 2*NI*NI elements [default: 100].
--pickle=PREFIX
 Pickle reduced discretizaion, as well as reductor and high-dimensional discretization to files with this prefix.
-p, --plot-err Plot error.
--plot-solutions
 Plot some example solutions.
--plot-error-sequence
 Plot reduction error vs. basis size.
--product=PROD Product (euclidean, h1) w.r.t. which to orthonormalize and calculate Riesz representatives [default: h1].
--reductor=RED Reductor (error estimator) to choose (traditional, residual_basis) [default: residual_basis]
--test=COUNT Use COUNT snapshots for stochastic error estimation [default: 10].
--ipython-engines=COUNT
 If positive, the number of IPython cluster engines to use for parallel greedy search. If zero, no parallelization is performed. [default: 0]
--ipython-profile=PROFILE
 IPython profile to use for parallelization.
--cache-region=REGION
 Name of cache region to use for caching solution snapshots (NONE, MEMORY, DISK, PERSISTENT) [default: NONE]
--list-vector-array
 Solve using ListVectorArray[NumpyVector] instead of NumpyVectorArray.
--no-visualize-refinement
 Do not visualize the training set refinement indicators.
--validation-mus=VALUE
 Size of validation set. [default: 0]
--rho=VALUE Maximum allowed ratio between error on validation set and on training set [default: 1.1].
--gamma=VALUE Weight factor for age penalty term in refinement indicators [default: 0.2].
--theta=VALUE Ratio of elements to refine [default: 0.].

pymordemos.thermalblock_adaptive.thermalblock_demo(args)[source]
thermalblock_gui module

Thermalblock with GUI demo

Usage:
thermalblock_gui.py [-h] [–product=PROD] [–grid=NI] [–testing]
[–help] XBLOCKS YBLOCKS SNAPSHOTS RBSIZE
Arguments:

XBLOCKS Number of blocks in x direction.

YBLOCKS Number of blocks in y direction.

SNAPSHOTS Number of snapshots for basis generation per component.
In total SNAPSHOTS^(XBLOCKS * YBLOCKS).

RBSIZE Size of the reduced basis

Options:
--grid=NI Use grid with 2*NI*NI elements [default: 60].
--product=PROD Product (euclidean, h1) w.r.t. which to orthonormalize and calculate Riesz representatives [default: h1].
--testing load the gui and exit right away (for functional testing)
-h, --help Show this message.

class pymordemos.thermalblock_gui.AllPanel(parent, reduced_sim, detailed_sim)[source]

Bases: object


class pymordemos.thermalblock_gui.DetailedSim(args)[source]

Bases: pymordemos.thermalblock_gui.SimBase

Methods

DetailedSim solve

class pymordemos.thermalblock_gui.ParamRuler(parent, sim)[source]

Bases: object

Methods

ParamRuler enable

class pymordemos.thermalblock_gui.RBGui(args)[source]

Bases: QMainWindow


class pymordemos.thermalblock_gui.ReducedSim(args)[source]

Bases: pymordemos.thermalblock_gui.SimBase

Methods

ReducedSim solve

class pymordemos.thermalblock_gui.SimBase(args)[source]

Bases: object


class pymordemos.thermalblock_gui.SimPanel(parent, sim)[source]

Bases: object

Methods

SimPanel solve_update
thermalblock_simple module

Simplified version of the thermalblock demo.

Usage:
thermalblock_simple.py MODEL ALG SNAPSHOTS RBSIZE TEST
Arguments:

MODEL High-dimensional model (pymor, fenics, ngsolve, pymor-text).

ALG The model reduction algorithm to use
(naive, greedy, adaptive_greedy, pod).

SNAPSHOTS naive: ignored

greedy/pod: Number of training_set parameters per block
(in total SNAPSHOTS^(XBLOCKS * YBLOCKS) parameters).

adaptive_greedy: size of validation set.

RBSIZE Size of the reduced basis.

TEST Number of parameters for stochastic error estimation.


pymordemos.thermalblock_simple.discretize_fenics()[source]

pymordemos.thermalblock_simple.discretize_ngsolve()[source]

pymordemos.thermalblock_simple.discretize_pymor()[source]

pymordemos.thermalblock_simple.discretize_pymor_text()[source]

pymordemos.thermalblock_simple.main()[source]

pymordemos.thermalblock_simple.reduce_adaptive_greedy(d, reductor, validation_mus, basis_size)[source]

pymordemos.thermalblock_simple.reduce_greedy(d, reductor, snapshots, basis_size)[source]

pymordemos.thermalblock_simple.reduce_naive(d, reductor, basis_size)[source]

pymordemos.thermalblock_simple.reduce_pod(d, reductor, snapshots, basis_size)[source]